summarise_each为两个变量

时间:2015-02-06 14:29:54

标签: r dplyr summary

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

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)

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

1 个答案:

答案 0 :(得分:0)

我在操纵谷歌问这个问题,而布兰登赫尔给了我一个答案,我调整了进入我想要的最终形式。在这里,如果其他人发现他们需要做类似的事情:

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)

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