Writing a function to automate Wilcoxon signed ranks

Hello, everyone. Sorry if this is an elementary question, but I've been trying to get this to work for almost an hour and a half without success. I know there's probably a premade function to do this out there somewhere, but I'm writing this one myself as a self-imposed challenge, since my school offers little formal training in R.

I have a n=16 dataset defined as "x", with null hypothesis median m=160. I want to write a function that will generate a vector of Wilcoxon signed ranks for each value of the dataset given the arguments "x" and "m". I tried first without using a function, and it turned out fine:

>xraw<-c(176.9,158.3,152.1,158.8,172.4,169.8,159.7,162.7,156.6,174.5,184.4,165.2,147.8,177.8,160.1,160.5)

> x<-sort(xraw)

> demedx<-x-160

> avdmx<-abs(demedx)

> r<-rank(avdmx)

> w<-replicate(16,0)

> for(i in 1:16){

+ if (demedx[i]>0){w[i]<-r[i]}

+ else {w[i]<-(-r[i])}

+ }

> print(w)

[1] -11 -9 -7 -5 -4 -2 1 3 6 8 10 12 13 14 15

[16] 16

>

When I tried to write a function to automate the process, however, it only returned the first Wilcoxon signed rank. The others were zeroes:

> xraw<-c(176.9,158.3,152.1,158.8,172.4,169.8,159.7,162.7,156.6,174.5,184.4,165.2,147.8,177.8,160.1,160.5)

> x<-sort(xraw)

> Wilcoxon_sr <- function(x,m){

+ demedx<-(x-m)

+ avdmx<-abs(demedx)

+ r<-rank(avdmx)

+ w<-replicate(NROW(x),0)

+ for(i in 1:NROW(x)){

+ if (demedx[i]>0){

+ w<-replace(w,i,r[i])}

+ else {w<-replace(w,i,-r[i])}

+ return(w)

+ print(w)

+ }

+ }

>

> Wilcoxon_sr(x,160)

[1] -11 0 0 0 0 0 0 0 0 0 0 0 0 0 0

[16] 0

Does anyone have an idea where I might have gone wrong?

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.