You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何统计R数据框中逗号分隔的犬种出现次数

统计问卷中犬种的出现次数

针对你提供的问卷数据,这里有两种高效的方法来统计每个犬种在dogs_owned和dogs_fav列的出现次数:

方法一:基础R实现

无需额外安装工具包,直接用基础函数完成统计:

dogs_owned <-c("labrador, golden", "golden","pitbull, chihuahua")
dogs_fav <- c("beagle", "labrador, shepherd", "chihuahua, pitbull")
test <- data.frame(dogs_owned,dogs_fav)

list <- c("labrador", "golden","pitbull","chihuahua","beagle","shepherd")
list_test <- data.frame(list)

# 拆分列内容并统计各犬种出现次数
owned_counts <- table(unlist(strsplit(test$dogs_owned, ", ")))
fav_counts <- table(unlist(strsplit(test$dogs_fav, ", ")))

# 将统计结果匹配到目标数据框,未出现的犬种填充0
list_test$count_own <- as.integer(owned_counts[list_test$list])
list_test$count_fav <- as.integer(fav_counts[list_test$list])
list_test[is.na(list_test)] <- 0

运行后list_test的最终结果:

list count_own count_fav
1   labrador         1         1
2     golden         2         0
3    pitbull         1         1
4  chihuahua         1         1
5     beagle         0         1
6   shepherd         0         1

方法二:tidyverse工具包实现

如果习惯使用tidyverse的语法风格,代码逻辑更直观:

library(tidyverse)

dogs_owned <-c("labrador, golden", "golden","pitbull, chihuahua")
dogs_fav <- c("beagle", "labrador, shepherd", "chihuahua, pitbull")
test <- data.frame(dogs_owned,dogs_fav)

list <- c("labrador", "golden","pitbull","chihuahua","beagle","shepherd")
list_test <- data.frame(list)

# 拆分多行并统计拥有犬种的次数
own_stats <- test %>%
  separate_rows(dogs_owned, sep = ", ") %>%
  count(dogs_owned, name = "count_own")

# 拆分多行并统计最喜欢犬种的次数
fav_stats <- test %>%
  separate_rows(dogs_fav, sep = ", ") %>%
  count(dogs_fav, name = "count_fav")

# 合并统计结果到目标数据框,缺失值填充0
list_test <- list_test %>%
  left_join(own_stats, by = c("list" = "dogs_owned")) %>%
  left_join(fav_stats, by = c("list" = "dogs_fav")) %>%
  replace(is.na(.), 0)

该方法通过separate_rows将每行的多个犬种拆分为独立行,再用count完成次数统计,最后合并到list_test中,结果与基础R方法完全一致。

内容的提问来源于stack exchange,提问作者Pom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 02:50:39