【问题标题】:Count a list of specific strings in an R data frame计算 R 数据框中特定字符串的列表
【发布时间】:2023-01-18 21:39:15
【问题描述】:

我有一个包含 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 个不同字符串的列表情况列,我希望我的输出是这样的。

输出

Eye color   Sound of your voice   Certain disease    Size of a palm    Hair color   Height
    3           2                      1                   1              2          2

【问题讨论】:

  • 试试这个:table(unlist(strsplit(df$Conditions, ', ')))
  • @Sotos 这个仅适用于单次输入。用逗号分隔的多个条目不适用于表功能
  • 你是什​​么意思?我得到正确的结果。注意你有两个Eye color和一个Eye Color(大写C
  • @Sotos 我纠正了我的错误。是的,我在逗号后用空格粘贴了我的数据字符串。我现在从您的第一条评论中删除了您的空间,是的,它现在可以使用了。但是如果我将结果与 excel 进行比较,我会得到不同的结果。假设,如果我在 excel 中搜索 Eye Color,它会显示找到的 1412 个结果,而 R 显示的结果是 42606。

标签: r string dataframe count unique


【解决方案1】:

由于我不知道数据的确切结构,我假设数据如下

数据

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`)

输出

【讨论】:

    猜你喜欢
    • 2017-12-03
    • 2020-04-09
    • 2018-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多