R 按名称分组并执行统计(t 检验)

R grouping by name and perform stats (t-test)

我有两个data.frames:

word1=c("a","a","a","a","b","b","b")    
word2=c("a","a","a","a","c","c","c")
values1 = c(1,2,3,4,5,6,7)
values2 = c(3,3,0,1,2,3,4)
df1 = data.frame(word1,values1)
df2 = data.frame(word2,values2)

df1:

  word1  values1
1   a      1
2   a      2
3   a      3
4   a      4
5   b      5
6   b      6
7   b      7

df2:

 word2  values2
1   a     3
2   a     3
3   a     0
4   a     1
5   c     2
6   c     3
7   c     4

我想将这些数据帧拆分为 word*,并在 R 中执行两个样本 t.tests。

例如,单词"a"在两个data.frames中。单词 "a" 的 data.frames 之间的 t.test 是什么?并对 data.frames.

中的所有单词执行此操作

结果是 data.frame(result):

   word  tvalues
1   a    0.4778035

谢谢

找到两个数据帧共有的词,然后遍历这些词,对两个数据帧进行子集化并对子集执行t.test

例如:

df1 <- data.frame(word=sample(letters[1:5], 30, replace=TRUE),
                  x=rnorm(30))

df2 <- data.frame(word=sample(letters[1:5], 30, replace=TRUE),
                  x=rnorm(30))

common_words <- sort(intersect(df1$word, df2$word))

setNames(lapply(common_words, function(w) {
  t.test(subset(df1, word==w, x), subset(df2, word==w, x))
}), common_words)

这是一个returns列表,其中每个元素都是t.test中一个常用词的输出。 setNames 只是命名列表元素,以便您可以看到它们对应的单词。

请注意,我在这里创建了新的示例数据,因为您的示例数据只有一个共同词 (a),因此与您的真实问题并不十分相似。


如果你只想要一个统计矩阵,你可以这样做:

t(sapply(common_words, function(w) {
  test <- t.test(subset(df1, word==w, x), subset(df2, word==w, x))
  c(test$statistic, test$parameter, p=test$p.value, 
    `2.5%`=test$conf.int[1], `97.5%`=test$conf.int[2])
}))

##            t        df          p       2.5%      97.5%
## a  0.9141839  8.912307 0.38468553 -0.4808054  1.1313220
## b -0.2182582  7.589109 0.83298193 -1.1536056  0.9558315
## c -0.2927253  8.947689 0.77640684 -1.5340097  1.1827691
## d -2.7244728 12.389709 0.01800568 -2.5016301 -0.2826952
## e -0.3683153  7.872407 0.72234501 -1.9404345  1.4072499