【问题标题】:Use stringr and str_count to return the number of unique words in a string使用 stringr 和 str_count 返回字符串中唯一单词的数量
【发布时间】:2020-11-26 10:59:05
【问题描述】:

有没有办法使用 str_count 来计算字符串中的唯一单词? 我希望下面的简单代码返回 2 而不是 6。

library(tidyverse)

string <- "Z AD Banana EW Z AD Z AD X" 

str_count(string, "Z|AD")

Returns: 6

【问题讨论】:

    标签: r stringr


    【解决方案1】:

    一种方法是提取所有满足模式的值,然后计算唯一值。

    library(dplyr)
    library(stringr)
    
    n_distinct(str_extract_all(string, "Z|AD")[[1]])
    #[1] 2
    

    这可以用基数 R 写成:

    length(unique(regmatches(string, gregexpr("Z|AD", string))[[1]]))
    

    【讨论】:

    • 这很好地与上面的字符串一起工作。但是当我尝试将它应用到我的数据集 (mutate = n_distinct(str_extract_all(string_var, pattern))[[1]]) 时,它会为每一行返回相同的值。
    • 如果您有不需要[[1]] 的列值。试试df %&gt;% mutate(temp = str_extract_all(string, 'Z|AD'), n = map_dbl(temp, n_distinct))
    • 太棒了!为什么我需要扔地图?是因为 str_extract_all 返回一个列表吗?
    • 是的,在示例中因为您只有一个字符串,所以我使用了[[1]],但如果您有多个字符串,您需要使用maplapply
    【解决方案2】:

    我们可以使用

    library(stringr)
    library(purrr)
    map_lgl(c("Z", "AD"), ~ str_detect(string, .x)) %>% sum
    #[1] 2
    

    【讨论】:

      猜你喜欢
      • 2014-03-29
      • 2018-05-14
      • 1970-01-01
      • 1970-01-01
      • 2018-09-15
      • 1970-01-01
      • 1970-01-01
      • 2022-01-09
      • 2015-03-15
      相关资源
      最近更新 更多