Count occurrences of multiple strings in one character variable

时间:2018-03-09 19:08:23

标签: r stringi rtweet

I have a dataset of tweets downloaded with rtweet. And i'd like to see how many times three different strings occur in the variable x$mentions_screen_name.

The key thing I'm trying to do is do a count of how many times 'A' occurs, then 'B', then 'C'. So my attempt at reproducing this is as follows.

#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))

4 个答案:

答案 0 :(得分:1)

You can do this easily by summing the columns after running grepl() through sapply().

colSums(sapply(var, grepl, df$var1))
#  A  B  C 
# 72 72 69 

答案 1 :(得分:1)

如果您想计算所有出现次数(也是一个字符串中的多个出现次数),您可以使用str_count包中的stringr

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

答案 2 :(得分:1)

我认为您可能想要与其他人发布的内容不同的内容。我可能错了,但你用的是这句话:

 '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

如果我对我的误解表示歉意。

答案 3 :(得分:0)

使用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