【问题标题】:Establishing counts within inconsistent character strings in R?在R中的不一致字符串中建立计数?
【发布时间】:2021-11-10 17:51:15
【问题描述】:

我有一个数据集,其中有调查对象针对他们的偏好单击“所有适用”选项,并将每个选择的选项返回为一个用逗号分隔的字符串。

因此,一些示例响应可能是:

  • “网络、期刊、社交媒体组”
  • “期刊”
  • “网络、社交媒体组”
  • “网络,期刊”

有没有办法有效地计算列中出现的每个子字符串的计数?所需的输出将是

 "Networking: 4"
 "Journals: 3"
 "Social Media Groups: 2"

【问题讨论】:

    标签: r string


    【解决方案1】:

    这是一个tidyverse 替代方案:

    library(tidyverse)
    df %>% 
        mutate(string = strsplit(as.character(string), ",")) %>% 
        unnest(string) %>% 
        count(String = str_trim(string))
    
    String                  n
      <chr>               <int>
    1 Journals                3
    2 Networking              3
    3 Social Media Groups     2
    

    数据:

    df <- structure(list(string = c("Networking, Journals, Social Media Groups", 
    "Journals", "Networking, Social Media Groups", "Networking, Journals"
    )), row.names = c(NA, -4L), class = c("tbl_df", "tbl", "data.frame"
    ))
    

    【讨论】:

    • 按照发布的方式运行它会出现错误:“计数错误(。,字符串 = str_trim(字符串)):未使用的参数(字符串 = str_trim(字符串))”
    • 你加载了tidyverse。我无法重现该错误。版本 tidyverse_1.3.1.
    • 知道了,出于某种原因,需要完全重新启动 R 而不是 rm(list=ls()) 以清除环境。
    【解决方案2】:

    数据

    df <- structure(list(string = c("Networking, Journals, Social Media Groups","Journals", "Networking, Social Media Groups", "Networking, Journals")), row.names = c(NA, -4L), class = c("tbl_df", "tbl", "data.frame"))
    
    
    # A tibble: 4 x 1
      string                                   
      <chr>                                    
    1 Networking, Journals, Social Media Groups
    2 Journals                                 
    3 Networking, Social Media Groups          
    4 Networking, Journals 
    

    代码

    library(tidyverse)
    
    df %>% 
      separate_rows(string,sep = ", ") %>% 
      count(string)
    
    # A tibble: 3 x 2
      string                  n
      <chr>               <int>
    1 Journals                3
    2 Networking              3
    3 Social Media Groups     2
    

    【讨论】:

    • 完全按照您发布的方式运行会导致错误:“count(., string) : object 'string' not found”。
    • 在我的示例中,df 是我的 data.frame 的名称,string 是包含数据的列的名称。您需要更改它们以使用您的数据
    【解决方案3】:

    我们可以使用base R

    table(unlist(strsplit(df$string, ",\\s+")))
    

    -输出

                Journals          Networking Social Media Groups 
                      3                   3                   2 
    

    数据

    df <- structure(list(string = c("Networking, Journals, Social Media Groups", 
    "Journals", "Networking, Social Media Groups", "Networking, Journals"
    )), row.names = c(NA, -4L), class = c("tbl_df", "tbl", "data.frame"
    ))```
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-18
      • 1970-01-01
      • 2018-12-02
      • 2020-02-27
      • 1970-01-01
      • 2017-07-09
      相关资源
      最近更新 更多