【问题标题】:Summarize word count in dplyr pipe总结 dplyr 管道中的字数
【发布时间】:2018-04-27 08:41:42
【问题描述】:

我想生成 dplyr 管道中字数频率的频率计数摘要。它必须在 dplyr 管道中,因为我实际上是从 bigrquery 查询的,它充当 dplyr 管道。

假设我有这样的数据:

tf1 <- tbl_df(data.frame(row= c(1:5), body=c("tt t ttt j ss oe", "kpw eero", "pow eir sap r", "s", "oe")))

我想要一个字数的摘要(类似这样):

   n_words freq
1   0    0
2   1    2
3   2    1
4   3    0
5   4    1
6   5    0
7   6    1

但我需要在 dplyr 管道中执行此操作(如下所示不起作用)

###NOT WORK
tf1 %>%
wordcount(body,sep=" ", count.function=sum) 

【问题讨论】:

    标签: r string dplyr


    【解决方案1】:

    这是另一个想法,它也使用complete 来获取所有值,

    library(tidyverse)
    
    tf1 %>% 
       mutate(n_words = stringr::str_count(body, ' ') + 1) %>% 
       count(n_words) %>% 
       complete(n_words = 0:max(n_words))
    

    给出,

    # A tibble: 7 x 2
      n_words     n
        <dbl> <int>
    1      0.    NA
    2      1.     2
    3      2.     1
    4      3.    NA
    5      4.     1
    6      5.    NA
    7      6.     1
    

    【讨论】:

    • 替代字数统计方法:stringi::stri_count_words(body)
    【解决方案2】:
    library(dplyr)
    library(stringr)
    tf1 %>% mutate(wordcount = str_split(body, " ") %>% lengths()) %>% count(wordcount)
    ## # A tibble: 4 x 2
    ##   wordcount     n
    ##       <int> <int>
    ## 1         1     2
    ## 2         2     1
    ## 3         4     1
    ## 4         6     1
    

    str_split(tf1$body, " ") 返回

    [[1]]
    [1] "tt"  "t"   "ttt" "j"   "ss"  "oe" 
    
    [[2]]
    [1] "kpw"  "eero"
    
    [[3]]
    [1] "pow" "eir" "sap" "r"  
    
    [[4]]
    [1] "s"
    
    [[5]]
    [1] "oe"
    

    lengths计算每个列表元素的长度,因此

    str_split(tf1$body, " ") %>% lengths()
    ## [1] 6 2 4 1 1
    

    这通过使用mutate添加为列wordcount

    count 返回在列wordcount 中找到值的次数并将其存储为列n

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-18
      • 1970-01-01
      • 2016-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-14
      • 2021-06-30
      相关资源
      最近更新 更多