【问题标题】:Splitting Strings and Generating Frequency Tables in R在 R 中拆分字符串并生成频率表
【发布时间】:2012-01-30 08:40:14
【问题描述】:

我在 R 数据框中有一列公司名称,如下所示:

"ABC Industries"  
"ABC Enterprises"  
"123 and 456 Corporation"  
"XYZ Company"

等等。我正在尝试生成此列中出现的每个单词的频率表,例如,如下所示:

Industries   10  
Corporation  31  
Enterprise   40  
ABC          30  
XYZ          40  

我对 R 比较陌生,所以我想知道一个解决这个问题的好方法。我应该拆分字符串并将每个不同的单词放入一个新列吗?有没有办法用一个单词将多单词行分成多行?

【问题讨论】:

    标签: r string split frequency


    【解决方案1】:

    您可以使用包tidytextdplyr

    set.seed(42)
    
    text <- c("ABC Industries", "ABC Enterprises", 
           "123 and 456 Corporation", "XYZ Company")
    
    data <- data.frame(category = sample(text, 100, replace = TRUE),
                       stringsAsFactors = FALSE)
    
    library(tidytext)
    library(dplyr)
    
    data %>%
      unnest_tokens(word, category) %>%
      group_by(word) %>%
      count()
    
    #> # A tibble: 9 x 2
    #> # Groups:   word [9]
    #>          word     n
    #>         <chr> <int>
    #> 1         123    29
    #> 2         456    29
    #> 3         abc    45
    #> 4         and    29
    #> 5     company    26
    #> 6 corporation    29
    #> 7 enterprises    21
    #> 8  industries    24
    #> 9         xyz    26
    

    【讨论】:

      【解决方案2】:

      这是另一个单线。它使用paste() 将所有列条目组合成一个长文本字符串,然后将其拆分并制成表格:

      text <- c("ABC Industries", "ABC Enterprises", 
               "123 and 456 Corporation", "XYZ Company")
      
      table(strsplit(paste(text, collapse=" "), " "))
      

      【讨论】:

      • +1 太好了,我只会添加 split="\\s{1,}" 以使其更健壮
      • @WojciechSobala 是的——我有同样的想法,它可能更好/更接近 OP 想要的。 split = "\\s+"split = "[[:space:]]+" 是另外两个完全相同的选项。
      【解决方案3】:

      如果你愿意,你可以用一条线来做:

      R> text <- c("ABC Industries", "ABC Enterprises", 
      +            "123 and 456 Corporation", "XYZ Company")
      R> table(do.call(c, lapply(text, function(x) unlist(strsplit(x, " ")))))
      
              123         456         ABC         and     Company 
                1           1           2           1           1 
      Corporation Enterprises  Industries         XYZ 
                1           1           1           1 
      R> 
      

      这里我使用strsplit()来打破每个入口介绍组件;这将返回一个列表(在列表中)。我使用do.call(),所以只需将所有结果列表连接到一个向量中,table() 进行汇总。

      【讨论】:

      • 非常感谢。我一直在摆弄原始代码,我发现我得到了相同的结果: table(unlist(strsplit(text, " "))) lapply() 和 do.call() 的用途是什么?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-19
      • 1970-01-01
      • 2022-11-03
      • 1970-01-01
      • 2015-03-06
      • 1970-01-01
      • 2018-09-25
      相关资源
      最近更新 更多