【问题标题】:R grouping by name and perform stats (t-test)R 按名称分组并执行统计信息(t 检验)
【发布时间】:2015-02-20 21:15:33
【问题描述】:

我有两个 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

谢谢

【问题讨论】:

    标签: r statistics dataframe text-mining


    【解决方案1】:

    找到两个数据帧共有的单词,然后循环遍历这些单词,对两个数据帧进行子集化并对子集执行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
    

    【讨论】:

    • 但是如何创建一个只有 p 值的 data.frame(表)?例如:“e”“0.2731”,跟随您的 data.frames 值。谢谢
    猜你喜欢
    • 1970-01-01
    • 2022-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-10
    相关资源
    最近更新 更多