2017-05-07 121 views
4

我有一個包含實驗數據的數據集。 每天我有新的觀察在未來計算for循環中的p值

我的DF的與列A虛構例子: 天:天指數 組一個:數據控制 組b:數據處理。

structure(list(day = c(1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 3L), group_a = c(4L, 
2L, 3L, 1L, 1L, 4L, 3L, 2L, 4L), group_b = c(3L, 4L, 2L, 2L, 
2L, 2L, 3L, 4L, 5L)), .Names = c("day", "group_a", "group_b"), class = "data.frame", row.names = c(NA, 
-9L)) 

我想這個子集數據集中,應用像Wilcoxon符號秩檢驗:

test <- wilcox.test(df$group_a, df$group_b, alternative = 'g') 
test$p.value 

在這個例子中我申請測試在整個數據集。

我想它適用於1天,然後1天,2等,終於等到一個看起來像(虛構數據)名單:

day p-value 
1 0.02 
2 0.03 
3 0.3 

如何申請測試的for循環超過「一天」,但在「累計」天數?

回答

1

您可以使用Reduceaccumulate = TRUE

p_value <- do.call(rbind, lapply(Reduce(rbind, split(df, df$day), accumulate = TRUE), 
       function(i) wilcox.test(i$group_a, i$group_b, alternative = 'g')$p.value)) 
p_value 
#   [,1] 
#[1,] 0.7928919 
#[2,] 0.7768954 
#[3,] 0.7084401 

整潔的輸出,

final_df <- data.frame(day = unique(df$day), p_value) 

final_df 
# day p_value 
#1 1 0.7928919 
#2 2 0.7768954 
#3 3 0.7084401 
3

使用:

for (i in unique(df$day)) { 
    df$p.val[df$day == i] <- wilcox.test(df[df$day %in% 1:i,]$group_a, df[df$day %in% 1:i,]$group_b, alternative = 'g')$p.value 
} 

你:

> df 
    day group_a group_b  p.val 
1 1  4  3 0.7928919 
2 1  2  4 0.7928919 
3 2  3  2 0.7768954 
4 2  1  2 0.7768954 
5 2  1  2 0.7768954 
6 3  4  2 0.7084401 
7 3  3  3 0.7084401 
8 3  2  4 0.7084401 
9 3  4  5 0.7084401 

或者當你只是想在一個概括數據幀三個p值:

vec <- sapply(unique(df$day), 
       function(i) wilcox.test(df[df$day %in% 1:i,]$group_a, 
             df[df$day %in% 1:i,]$group_b, 
             alternative = 'g')$p.value) 

df2 <- data.frame(day = unique(df$day), p.val = vec) 

這給:

> df2 
    day  p.val 
1 1 0.7928919 
2 2 0.7768954 
3 3 0.7084401 
0

這也適用於:

library(data.table) 
setDT(df) 
test_pvals <- sapply(as.list(unique(df[, day])), function(x){ 
    df[day <= x, wilcox.test(group_a, group_b, alternative = 'g')$p.val] 
}) 
data.table(day = df[, unique(day)], p.val = test_pvals) 
## day  p.val 
## 1: 1 0.7928919 
## 2: 2 0.7768954 
## 3: 3 0.7084401 
+0

不。再次閱讀問題 – Sotos

+0

謝謝@索托斯。固定 –