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



我有两个数据帧:

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.test

例如,单词"a"在两个data.frame中。单词"a"的data.frames之间的t.test是多少?对两个数据帧中的所有单词都这样做。

结果是一个数据帧(结果):

   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)

这将返回一个列表,其中每个元素都是其中一个常用字的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

最新更新