1

我有一个用 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))
4

4 回答 4

1

如果您想计算所有出现次数(在单个字符串中也有多次出现),您可以str_countstringr包中使用。

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
于 2018-03-09T19:36:07.103 回答
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

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

于 2018-03-10T16:53:41.187 回答
1

grepl()您可以通过在运行后对列求和来轻松完成此操作sapply()

colSums(sapply(var, grepl, df$var1))
#  A  B  C 
# 72 72 69 
于 2018-03-09T19:22:56.960 回答
0

stringr使用and 的另一个选项sapply可能是:

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
于 2018-03-09T19:43:51.557 回答