这是您帖子中的数据集示例:
dataset <- data.frame(sample_01=c(100,50,90,40),
sample_02=c(120,49,87,43),
sample_02=c(110,48,80,42)
)
rownames(dataset) <- c("untreated", "drug1", "drug2", "drug3")
您的循环似乎很好,只需要两个修改:
2
首先,您应该从而不是从开始循环,1
因为您不想将第一行与自身进行比较(未经处理)。
第二,你应该将你的结果存储在一个列表中,而不是覆盖一个名为“results”的变量,因为这样你每次都会在循环中重写它,最后只会得到最后一行的答案。
以下是修改:
results <- list()
for (i in 2:nrow(dataset)) {
x <- dataset["untreated",]
y <- dataset[i,]
results[[i-1]] <- t.test(x,y)
}
现在您可以获得 p 值:
> sapply(results, getElement, "p.value")
[1] 0.008337497 0.033407617 0.006107201
或者,为了让事情变得更容易,您可以考虑使用一个包:
library(matrixTests)
> row_t_welch(dataset[-1,], dataset["untreated",])
obs.x obs.y obs.tot mean.x mean.y mean.diff var.x var.y stderr df statistic pvalue conf.low conf.high alternative mean.null conf.level
drug1 3 3 6 49.00000 110 -61.00000 1.000000 100 5.802298 2.039996 -10.513075 0.008337497 -85.50204 -36.497961 two.sided 0 0.95
drug2 3 3 6 85.66667 110 -24.33333 26.333333 100 6.489307 2.985027 -3.749758 0.033407617 -45.04393 -3.622734 two.sided 0 0.95
drug3 3 3 6 41.66667 110 -68.33333 2.333333 100 5.840472 2.093283 -11.699968 0.006107201 -92.41964 -44.247023 two.sided 0 0.95