James Burton
James Burton

Reputation: 27

Error: loop in R of each column?

I have some data and trying to do analysis. I dont know how to use R but I watched few videos on internet and trying to mimic the same test I need. What I want to do is trying to compare first four (1-4) rows with next four (4-8) rows. After I get result, I want to apply the same test to next column, therefore I will have 4 different p values. Please find an example image attached attached image. I have 4 columns in total which is the pilot test and will be performed with large column sizes later on. May I ask if someone can tell me what I am doing wrong and edit the code. I would be very glad for all helps.

Test = matrix(c(120, 115, 132, 117, 116,117,125,120,110,113,128,115),ncol=4, nrow = 4)
Test=t(Test)

Drug = matrix(c(88, 80, 85, 85, 83,84,90,83,83,79,86,82),ncol=4, nrow = 4)
Drug=t(Drug)
mydata<-cbind(Test,Drug)


for (i in 1:4)
wilcox.test(mydata[i,1:4],mydata[i,5:8], mu=0, alt="two.sided", paired=T,  conf.int=F,conf.level = 0.99, exact=T,correct=T)

Upvotes: 0

Views: 52

Answers (1)

I would recommend using a data.frame or data.table for this with a column specifying groups (corresponding to rows in the example, e.g. A, B, C), one column specifying test/drug and one column with values:

library(data.table)
Test <- c(120, 115, 132, 117, 116,117,125,120,110,113,128,115)
Drug <- c(88, 80, 85, 85, 83,84,90,83,83,79,86,82)
groups <- rep(c(rep("A", 4), rep("B", 4), rep("C", 4)), 2)
variable <- c(rep("test", length(Test)), rep("drug", length(Drug)))
dt <- data.table(group = groups, variable = variable, value = c(Test, Drug))

# >dt
#     group variable value
#  1:     A     test   120
#  2:     A     test   115
#  3:     A     test   132
#  4:     A     test   117
#  5:     B     test   116
#  6:     B     test   117
#  7:     B     test   125
#  8:     B     test   120
#  9:     C     test   110
# 10:     C     test   113
# 11:     C     test   128
# 12:     C     test   115
# 13:     A     drug    88
# 14:     A     drug    80
# 15:     A     drug    85
# 16:     A     drug    85
# 17:     B     drug    83
# 18:     B     drug    84
# 19:     B     drug    90
# 20:     B     drug    83
# 21:     C     drug    83
# 22:     C     drug    79
# 23:     C     drug    86
# 24:     C     drug    82
#     group variable value

Testing test-values vs drug-values per group is then a matter of:

dt_stat <- dt[, .(p_value = wilcox.test(value~variable, mu=0, alt="two.sided", paired = TRUE,
  conf.int = FALSE, conf.level = 0.99,exact = TRUE, correct = TRUE)$p.value),
  by = .(group)]

# > dt_stat
#    group    p_value
# 1:     A 0.09751254
# 2:     B 0.09751254
# 3:     C 0.12500000

Upvotes: 1

Related Questions