[英]Count a list of specific strings in an R data frame
我有一个包含 5 列的数据框,但我对一列“条件”感兴趣。 在条件列中,我需要找到一种方法来计算单元格中特定条目的数量。 每个列单元格可以有一个条目或多个由(, )分隔的条目。 所以我的数据框看起来像
S.NO Conditions
11 Eye Color
12 Sound of your voice
13 Certain disease,Size of a palm,Eye Color
16 Eye Color,Hair color
17 Hair color,Height
18 Sound of your voice,Height
我想一次计算所有不同的条目/字符串。 我在条件列中总共有 35 个不同字符串的列表,我想要我的 Output 这样的东西。
OUTPUT
Eye color Sound of your voice Certain disease Size of a palm Hair color Height
3 2 1 1 2 2
由于我不知道数据的确切结构,我假设数据如下
data <- tribble(
~Conditions, ~value,
'Eye color', '3',
'Sound of your voice', '2',
'Certain disease, Size of a palm, Eye color', '1,1,2',
'Eye color, Hair color', '2,2',
'Hair color, Height', '3,1',
'Sound of your voice, Height', '1,4'
)
对于上面的数据我们可以写下面的代码来得到预期的结果
library(tidyverse)
Conditions <- unlist(strsplit(data$Conditions,','))
value <- unlist(strsplit(data$value,','))
df <- bind_cols(Conditions,value) %>% mutate(Conditions=trimws(`...1`)) %>%
arrange(Conditions) %>% group_by(Conditions) %>% mutate(row=row_number()) %>%
pivot_wider(row,names_from = Conditions, values_from = `...2`)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.