【发布时间】: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
【问题讨论】:
有没有办法使用 str_count 来计算字符串中的唯一单词? 我希望下面的简单代码返回 2 而不是 6。
library(tidyverse)
string <- "Z AD Banana EW Z AD Z AD X"
str_count(string, "Z|AD")
Returns: 6
【问题讨论】:
一种方法是提取所有满足模式的值,然后计算唯一值。
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]]))
【讨论】:
[[1]] 的列值。试试df %>% mutate(temp = str_extract_all(string, 'Z|AD'), n = map_dbl(temp, n_distinct))
[[1]],但如果您有多个字符串,您需要使用map 或lapply。
我们可以使用
library(stringr)
library(purrr)
map_lgl(c("Z", "AD"), ~ str_detect(string, .x)) %>% sum
#[1] 2
【讨论】: