0

I'm pretty new to the R programming, but I am ever learning :)

I want to conduct a paired Wilcoxon Rank Sum test of before and after measurements. My subjects have gotten 4 different types of treatments (i.e. treatment as factor w/ 4 levels). My data is ordinal.

I have a data frame containing 3 columns:

  • Before
  • After
  • Type of treatment

Can I run the wilcox.test while subsetting the different types of treatments?

I ran the wilcox.test as follows:

wilcox.test(Before,After,paired=TRUE)

how do I edit this code to subset for my types of treatment?

Hope there is someone able to help me... :)


Before | After | Treatment
------ | ------ | ---------
2 | 2 | SH
2 | 1 | SH
2 | 2 | SH
1 | 1 | SH
2 | 2 | OH
2 | 2 | OH
2 | 2 | OH
2 | 1 | OH
2 | 1 | SA
2 | 1 | SA
1 | 1 | SA
2 | 2 | SA
2 | 2 | OA
2 | 3 | OA
1 | 2 | OA
2 | 2 | OA

Nakita
  • 3
  • 5

1 Answers1

0

Use split to make a list of your groups and then lapply over the list...

x <- read.csv(text = "Before|After|Treatment
2|2|SH
2|1|SH
2|2|SH
1|1|SH
2|2|OH
2|2|OH
2|2|OH
2|1|OH
2|1|SA
2|1|SA
1|1|SA
2|2|SA
2|2|OA
2|3|OA
1|2|OA
2|2|OA", sep = "|")

x <- split(x, x$Treatment)
lapply(x, function(g) wilcox.test(g$Before, g$After, paired = T))

$OA

Wilcoxon signed rank test with continuity correction

data: g$Before and g$After V = 0, p-value = 0.3458 alternative hypothesis: true location shift is not equal to 0

$OH

Wilcoxon signed rank test with continuity correction

data: g$Before and g$After V = 1, p-value = 1 alternative hypothesis: true location shift is not equal to 0

$SA

Wilcoxon signed rank test with continuity correction

data: g$Before and g$After V = 3, p-value = 0.3458 alternative hypothesis: true location shift is not equal to 0

$SH

Wilcoxon signed rank test with continuity correction

data: g$Before and g$After V = 1, p-value = 1 alternative hypothesis: true location shift is not equal to 0

emilliman5
  • 5,816
  • 3
  • 27
  • 37
  • It's working with the split. I'm now having a list of 4 under x :) But I get this error message when using lapply: – Nakita May 26 '17 at 12:28
  • "Error in g$Before : $ operator is invalid for atomic vectors". When checking g$Before "> is.atomic(g$Before)" I get this message: "Error: object 'g' not found" – Nakita May 26 '17 at 12:34
  • If you copy and paste all of the code it runs just fine.`g` only exists while `lapply` is running which is why `is.atomic(g$Before)` gives an error. You will need to provide your actual data for me to help, otherwise. See [this post](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) on how to do that. – emilliman5 May 26 '17 at 13:01
  • I tried it once again on my actual data and Voilá! ;) It worked! Thank you so much! You saved me! – Nakita May 27 '17 at 22:50