2016-04-29 68 views
0

我需要编写一个循环,它将在数据帧的小组上运行t-tests。我认为他们推荐使用for loop。 数据框中有271行。前260行需要分成13组,每组20个,并且必须在13组中的每一组上运行t-test在R中的数据帧组上运行循环

这是我用来运行整个数据帧上t-test代码:

t.test(a, c, alternative =c("two.sided"), mu=0, paired=TRUE, var.equal=TRUE, conf.level=0.95) 

我是一个编码小白,请帮忙! D:

回答

1

首先,我没有在这里看到data.frame。 ac似乎是矢量。我假设这两个矢量的长度都是271,而你想忽略最后的11个项目。所以你可以先扔掉这些东西:

a2 <- a[1:260] 
c2 <- c[1:260] 

现在你可以创建一个长度为260的矢量来确定子集的索引。 (有很多方法可以做到这一点,但我觉得这种方式很容易理解。)

indices <- as.numeric(cut(1:260, 20)) 
indices #just to show the output 

你可能要存储在列表输出。下面的代码再次不是最高效的,但容易理解。

result <- list() 
for (i in 1:20){ 
    result[[i]] <- t.test(a2[which(indices == i)], c2[which(indices == i)], 
         alternative = c("two.sided"), 
         mu = 0, paired = TRUE, var.equal = TRUE, 
         conf.level = 0.95) 
} 
result[[1]] #gives the results of the first t-test (items 1 to 20) 
result[[2]] # ... 

作为替代for -loop你也可以使用lapply这通常是更有效和更短些(但是不要紧,260个数据点):

result2 <- lapply(1:20, function(i) t.test(a2[which(indices == i)], 
              c2[which(indices == i)], 
              alternative = c("two.sided"), 
              mu = 0, paired = TRUE, var.equal = TRUE, 
              conf.level = 0.95)) 
result[[1]] # ... 

希望这是你的问题。

+0

嘿,对不起,我认为数据帧太大而且杂乱。 A和c代表数据帧中的列 非常感谢您的帮助! – Emilia