summarise_each 对于两个变量
summarise_each for two variables
我有一个看起来像这样的数据框:
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)
但是,正如我所说,我需要相对频率,所以我需要将上面的结果除以约翰和简分别产生的所有文本中的单词总数。获取百分比也很容易:
df %>%
group_by(lemma) %>%
summarise_each(funs(sum), n, total_words) %>%
mutate(percentage = n / total_words)
我想要的是用第二个示例中的百分比替换第一个示例中的总计数,这就是我卡住的地方。
我在 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)
简而言之,您需要分两个阶段执行此操作。
我有一个看起来像这样的数据框:
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)
但是,正如我所说,我需要相对频率,所以我需要将上面的结果除以约翰和简分别产生的所有文本中的单词总数。获取百分比也很容易:
df %>%
group_by(lemma) %>%
summarise_each(funs(sum), n, total_words) %>%
mutate(percentage = n / total_words)
我想要的是用第二个示例中的百分比替换第一个示例中的总计数,这就是我卡住的地方。
我在 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)
简而言之,您需要分两个阶段执行此操作。