r - 如何将逗号分隔的变量分组在同一列中?
问题描述
这是我的虚假数据:
#> id column
#> 1 blue, red, dog, cat
#> 2 red, blue, dog
#> 3 blue
#> 4 red
#> 5 dog, cat
#> 6 cat
#> 7 red, cat
#> 8 dog
#> 9 cat, red
#> 10 blue, cat
例如,我想告诉 Rdog and cat = animal
和red and blue = colour
. 我想基本上计算动物、颜色和两者的数量(以及最终百分比)。
#> id column newcolumn
#> 1 blue, red, dog, cat both
#> 2 red, blue, dog both
#> 3 blue colour
#> 4 red colour
#> 5 dog, cat animal
#> 6 cat animal
#> 7 red, cat both
#> 8 dog animal
#> 9 cat, red both
#> 10 blue, cat both
到目前为止,我只能通过执行以下操作来合计红色、蓝色、狗和猫的数量:
column.string<-paste(df$column, collapse=",")
column.vector<-strsplit(column.string, ",")[[1]]
column.vector.clean<-gsub(" ", "", column.vector)
table(column.vector.clean)
非常感谢您的帮助,这是我的示例错误数据:
df <- data.frame(id = c(1:10),
column = c("blue, red, dog, cat", "red, blue, dog", "blue", "red", "dog, cat", "cat", "red, cat", "dog", "cat, red", "blue, cat"))
解决方案
您可以在向量中定义所有可能animal
的 s 和s。colour
拆分column
逗号和测试:
animal <- c('dog', 'cat')
colour <- c('red', 'blue')
df$newcolumn <- sapply(strsplit(df$column, ',\\s*'), function(x) {
x <- x[x != "NA"]
if(!length(x)) return(NA)
if(all(x %in% animal)) 'animal'
else if(all(x %in% colour)) 'colour'
else 'both'
})
df
# id column newcolumn
#1 1 blue, red, dog, cat both
#2 2 red, blue, dog both
#3 3 blue colour
#4 4 red colour
#5 5 dog, cat animal
#6 6 cat animal
#7 7 red, cat both
#8 8 dog animal
#9 9 cat, red both
#10 10 blue, cat both
要计算比例,您可以使用prop.table
with table
:
prop.table(table(df$newcolumn, useNA = "ifany"))
#animal both colour
# 0.3 0.5 0.2
使用dplyr
,我们可以用逗号分隔行,为每行id
创建一个newcolumn
基于条件并计算比例。
library(dplyr)
df %>%
tidyr::separate_rows(column, sep = ',\\s*') %>%
group_by(id) %>%
summarise(newcolumn = case_when(all(column %in% animal) ~ 'animal',
all(column %in% colour) ~ 'colour',
TRUE ~ 'both'),
column = toString(column)) %>%
count(newcolumn) %>%
mutate(n = n/sum(n))
推荐阅读
- python - 与字符串字符作斗争
- java - 如何处理队列通道中的消息丢失?
- python - 在 NetworkX 中检查具有各种顶点标签的同构图的相等性
- android - Android - 用于处理 IllegalStateException 的 Kotlin 协程:无法访问主线程上的数据库
- r - 从向量中替换行和列数据框中的值
- python - 使用 statsmodels 创建残差图
- assembly - 组装中的错误(注册)计数器
- javascript - 尝试使用 javascript+ajax 上传文件时出现“MultipartException:当前请求不是多部分请求”(来自邮递员)
- javascript - 将一组值映射到百分比
- node.js - 在显示具有大选择列表的自适应卡(在 botframework 中)时,来自 bot 的大小限制(限制为 262144 字节)问题