2016-04-29 67 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