【发布时间】:2021-07-24 09:37:00
【问题描述】:
对于dplyr 的 ppl 来说,这可能是一个简单的问题 - 我想计算数据帧中字符数据的频率列表:
玩具数据:
df <- data.frame(
id = sample(1:5, 100, replace = TRUE),
v1 = sample(c(NA, rnorm(10)), 100, replace = TRUE),
v2 = sample(LETTERS, 100, replace = TRUE)
)
到目前为止我的尝试:
假设df 首先需要针对多个变量进行过滤。一旦完成,我就可以计算频率列表但输出不显示相应的字符值,所以我不知道哪个值具有哪个频率:
library(dplyr)
df %>%
filter(!is.na(v1) & !id == lag(id)) %>%
summarise(freq = sort(prop.table(table(v2)), decreasing = TRUE)*100)
freq
1 7.692308
2 6.410256
3 5.128205
4 5.128205
5 5.128205
6 5.128205
7 5.128205
8 5.128205
9 5.128205
10 5.128205
output clipped ...
所以我需要得到第二列,显示频率所属的值A、B、C 等。如何实现?
编辑:
哎呀,我想我明白了:
df %>%
filter(!is.na(v1) & !id == lag(id)) %>%
summarise(freq = sort(prop.table(table(v2)), decreasing = TRUE)*100,
value = names(sort(prop.table(table(v2)), decreasing = TRUE)))
【问题讨论】: