【发布时间】:2021-11-13 14:55:56
【问题描述】:
虚拟数据:
set.seed(4)
name <- sample(LETTERS[1:8], 500, replace = T)
id <- round(runif(500, min=1, max=200))
df <- data.frame(name, id)
我想检查 B 中唯一 id 的百分比,哪些是其他剩余的 name
预期的输出将是这样的:
name count pct_common
<chr> <int> <dbl>
1 A 17 29.3
2 C 18 31.0
3 D 16 27.6
4 E 22 37.9
5 F 14 24.1
6 G 16 27.6
7 H 20 34.5
到目前为止我的方法:
the_name <- 'B'
#Selecting the unique name, id combination for 'B'
df %>%
filter(name %in% the_name) %>%
distinct(name, id)-> list_id
#Checking which of these ids are already there for other names and then count them.
df %>%
filter( id %in% list_id$id) %>%
filter(!name %in% the_name) %>%
group_by(name) %>%
summarise(count=n()) %>%
mutate(pct_common= count/nrow(list_id)*100)
它正在完成工作,但是像这样创建一个单独的数据框似乎不是很优雅。此外,相对较大的数据框(数百万个观测值)需要更多时间。
有没有更好的方法来解决这个问题?
【问题讨论】: