每当行中的字符串中包含一个字符时,如何添加计数器? 数据

问题描述

我有一个数据框,其中大部分包含与模式列表匹配的字符。我正在尝试在最后添加一列,以计算该行中的列表被命中的次数。基本上,我要去的是

patterns <- c("Yes","No","Maybe")
df <- data.frame (first_column  = c("Why","Sure","But",...),second_column = c("Yes","Okay","If Only" ...),third_column = c("No","When","Maybe so" ...),fourth_column = c("But","I won't","Truth" ...)
                  )

在运行代码之后,在标记为“计数器”的第五列下,您将看到2、0、1 ... 现在,我通过一对嵌套的for循环和一个if语句来完成此操作。它适用于玩具数据集,但我认为如果对完整大小的数据尝试它会损坏。是否有使用dplyr,grepl或lapply的更好方法?我的直觉是dplyr,但我不确定该怎么做。我的代码如下:

filename = choose.files(caption='Select File')
cases = read.csv(filename)
cases = cbind(cases,counter=0)
l = nrow(cases)
col = ncol(cases)
for (i in 1:l){
  for (j in 1:col){
    if(cases[i,j] %in% patterns)
    {
      cases$counter[i]=cases$counter[i]+1
      }
    }
  
}

解决方法

尝试一下

df$counter <- rowSums(vapply(df,function(x,p) grepl(p,x),integer(nrow(df)),paste0(patterns,collapse = "|")))

输出

> df
  first_column second_column third_column fourth_column counter
1          Why           Yes           No           But       2
2         Sure          Okay         When       I won't       0
3          But       If Only     Maybe so         Truth       1
,

path1 <- "~directory/firm1" firm1 <- keyword_directory(path1,keyword = c('Company Information','Company Directory','Directory','Corporate Information','Corporate Directory'),surround_lines = 0,full_names = TRUE) 中,我们可以将dplyrrowwise结合使用:

c_across
,

我们可以使用mapreduce来按列进行操作

library(dplyr)
library(purrr)
df %>% 
  mutate(counter = map(patterns,~ rowSums(cur_data() == .x)) %>% 
                                reduce(`+`))
#  first_column second_column third_column fourth_column counter
#1          Why           Yes           No           But       2
#2         Sure          Okay         When       I won't       0
#3          But       If Only     Maybe so         Truth       0

数据

df <- structure(list(first_column = c("Why","Sure","But"),second_column = c("Yes","Okay","If Only"),third_column = c("No","When","Maybe so"
),fourth_column = c("But","I won't","Truth")),class = "data.frame",row.names = c(NA,-3L))