计算一个字符变量中多个字符串的出现次数

Count occurrences of multiple strings in one character variable

我有一个用 rtweet 下载的推文数据集。我想看看三个不同的字符串在变量 x$mentions_screen_name 中出现了多少次。

我要做的关键是计算 'A' 发生的次数,然后是 'B',然后是 'C'。所以我重现这个的尝试如下。

#These are the strings I would like to count
var<-c('A', 'B', 'C')
#The variable that contains the strings looks like this
library(stringi)
df<-data.frame(var1=stri_rand_strings(100, length=3, '[A-C]'))
#How do I count how many cases contain A, then B and then C.?
library(purrr)
df%>% 
  map(var, grepl(., df$var1))

您可以通过对 运行 grepl()sapply().

之后的列求和来轻松完成此操作
colSums(sapply(var, grepl, df$var1))
#  A  B  C 
# 72 72 69 

如果你想计算所有出现次数(因此在单个字符串中也有多次出现),你可以使用 stringr 包中的 str_count

map_int(var, ~sum(stringr::str_count(df$var1, .)))
[1]  90 112  98

否则,您可以使用str_detect

map_int(var, ~sum(stringr::str_detect(df$var1, .)))
[1] 66 71 70

另一个使用 stringrsapply 的选项可能是:

library(stringr)
set.seed(1)
df<-data.frame(var1=stri_rand_strings(100, length=3, '[A-C]'))

var<-c('A', 'B', 'C')
colSums(sapply(var, function(x,y)str_count(y, x), df$var1 ))
#A   B   C 
#101 109  90

我认为您可能想要与其他人发布的内容不同的内容。我可能是错的,但你使用的短语:

 'A' occurs, then 'B', then 'C'

向我表明您想检查某些事情是否按特定顺序发生。

如果是这种情况,我建议你把你的问题说得更明确一些。您提供了一个 MWE 示例,但它可以变得更小而不需要 stringi(我喜欢作为一个包),因为我怀疑您的推文在现实中看起来像 "ACB" .手工制作 3-5 个字符串可以在不加载另一个包的情况下完成此操作。还显示您想要的输出使问题更明确,不需要解释。

df <- data_frame(var1=c(
    "I think A is good But then C.",
    "'A' occurs, then 'B', then 'C'",
    "and a then lower with b that c will fail",
    NA,
    "what about A, B, C and another ABC",
    "CBA?",
    "last null"
))

var <- c('A', 'B', 'C')

library(stringi); library(dplyr)

df%>% 
    mutate(
        count_abc = stringi::stri_count_regex(
            var1, 
            paste(var, collapse = '.*?')
        ),
        indicator = count_abc > 0
    )

##   var1                                     count_abc indicator
## 1 I think A is good But then C.                    1 TRUE     
## 2 'A' occurs, then 'B', then 'C'                   1 TRUE     
## 3 and a then lower with b that c will fail         0 FALSE    
## 4 <NA>                                            NA NA       
## 5 what about A, B, C and another ABC               2 TRUE     
## 6 CBA?                                             0 FALSE    
## 7 last null                                        0 FALSE   

## or if you only care about the summary compute it directly
df%>% 
    summarize(
        count_abc = sum(stringi::stri_detect_regex(
            var1, 
            paste(var, collapse = '.*?')
        ), na.rm = TRUE)
    )


##   count_abc
## 1         3

如果我错了,我为我的误解道歉。