在R中如何统计tibble的list column指向另一data frame指定属性的次数?
问题解决:统计links中指向att="yes"的次数
错误原因
你的代码中使用large$id %in% .x会对匹配的id去重,比如第一个links里的两个3只会被视为一次匹配,导致统计结果少算一次。
正确方案
方案一:使用match保留重复匹配
library(tidyverse) a <- c(3, 3, NA, 5) b <- c(NA, 3, 4, 5) small <- tibble(id = c(1, 2), links = list(a, b)) large <- tibble(id = c(3, 4, 5), att = c("yes", "no", "maybe")) counted <- small %>% mutate(count_yes = map_int(links, ~ { # 为links中的每个元素匹配对应的att值 matched_att <- large$att[match(.x, large$id)] # 统计"yes"的数量,忽略NA sum(matched_att == "yes", na.rm = TRUE) })) print(counted) #> # A tibble: 2 × 3 #> id links count_yes #> <dbl> <list> <int> #> 1 1 <dbl [4]> 2 #> 2 2 <dbl [4]> 1
方案二:展开列表后分组统计(更直观的tidy风格)
counted <- small %>% # 把list列展开为多行 unnest(links) %>% # 关联large表获取对应的att值 left_join(large, by = c("links" = "id")) %>% # 按small的id分组统计 group_by(id) %>% summarise( count_yes = sum(att == "yes", na.rm = TRUE), # 把links重新合并为list列(还原原结构) links = list(links) ) %>% ungroup() print(counted) #> # A tibble: 2 × 3 #> id count_yes links #> <dbl> <int> <list> #> 1 1 2 <dbl [4]> #> 2 2 1 <dbl [4]>
两种方案都能得到正确的count_yes结果:2和1。
内容的提问来源于stack exchange,提问作者geoscience123
相关产品推荐
相关产品推荐

