不要在单个列上使用grep,而是在整个数据帧上使用grepl 作为字符矩阵。这将返回一个逻辑向量。将逻辑向量转换为与原始数据框相同维度的矩阵,然后运行which,指定arr.ind = TRUE。这将为您提供正则表达式的所有匹配项的行和列。
keywords <- c("knowledge management", "gestión del conocimiento")
npox <- grepl(paste(keywords, collapse = "|"), as.matrix(full), ignore.case = T)
which(matrix(npox, nrow = nrow(full)), arr.ind = TRUE)
#> row col
#> [1,] 16 8
#> [2,] 15 9
#> [3,] 15 10
#> [4,] 16 15
#> [5,] 16 23
例如,我们可以看到第 8 列第 16 行有一个匹配项。我们可以通过以下方式确认这一点:
full[16, 8]
#> [1] "The Impact of Human Resource Management Practices, Organisational
#> Culture, Organisational Innovation and Knowledge Management on Organisational
#> Performance in Large Saudi Organisations: Structural Equation Modeling With
#> Conceptual Framework"
我们看到这个单元格中存在“知识管理”。
如果您想将结果限制在某些列中,那么事后过滤掉结果可能是最简单的方法。例如,假设我将full 中的所有匹配项存储到名为matches 的变量中:
matches <- which(matrix(npox, nrow = nrow(full)), arr.ind = TRUE)
但我只对第 7、8 和 9 列的匹配感兴趣,然后我可以这样做:
matches[matches[,'col'] %in% c(7, 8, 9),]
#> row col
#> [1,] 16 8
#> [2,] 15 9