【问题标题】:summarise_each for two variablessummarise_each 两个变量
【发布时间】:2015-02-06 14:29:53
【问题描述】:

我有一个看起来像这样的数据框:

df <- data.frame(
    text = c(1:12),
    person = c(c(rep("John", 6)), c(rep("Jane", 6))),
    lemma  = c("he", "he", "he", "his", "it", "she", "he",
           "she", "she", "his", "it", "she"),
    n = c(8, 8, 3, 7, 10, 4, 12, 9, 3, 4, 2, 8),
    total_words = c(20, 49, 19, 39, 40, 30, 13, 30, 20, 34, 33, 15))

我要做的是获取汇总统计数据,以便我可以分别用 John 和 Jane 生成的所有文本来判断每个代词的相对频率。如果我想要的只是计数,那就很容易了:

library("dplyr")
library("tidyr")
df %>%
   group_by(person, lemma) %>%
   summarise_each(funs(sum), n) %>%
   spread(lemma, n)

但是,正如我所说,我需要相对频率,所以我需要将上述结果分别除以 John 和 Jane 生成的所有文本中的单词总数。获得百分比也很容易:

df %>%
group_by(lemma) %>%
summarise_each(funs(sum), n, total_words) %>%
mutate(percentage = n / total_words)

我想要将第一个示例中的总计数替换为第二个示例中的百分比,这就是我卡住的地方。

【问题讨论】:

  • 你应该添加预期的输出
  • 谢谢。我离开了我的电脑,但我想做的是得到总和,比如说,约翰在他所有六个文本中的“他的”除以他的总单词的总和(也就是说,他所有六个文本中的总字数的总和,但我想要他的代词和她的所有代词。我可以得到约翰和简各自产生的代词数量,以及所有代词的百分比,但我不能不要把两者放在同一张桌子上。

标签: r dplyr summary


【解决方案1】:

我在 manipulaR google 上问过这个问题,Brandon Hurr 给了我一个答案,我对其进行了调整以达到我想要的最终形式。在这里,以防其他人发现他们需要做类似的事情:

wordPerson <- df %>%
  group_by(person) %>%
  summarise(sumWords = sum(total_words))

df %>%
   group_by(lemma, person) %>%
   summarise_each(funs(sum), n, total_words) %>%
   inner_join(., wordPerson, by = "person") %>%
   mutate(percentage = n / sumWords) %>%
   select(person, lemma, percentage) %>%
   spread(lemma, percentage)

简而言之,您需要分两个阶段执行此操作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 2014-11-03
    • 1970-01-01
    • 2012-11-21
    • 2014-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多