【问题标题】:Grep in two or more columns of a dataframeGrep 在数据框的两列或多列中
【发布时间】:2022-08-21 12:35:47
【问题描述】:

我有一个数据框,我想知道某些字符串是否出现在某些列中,然后获取它们的行号,我正在使用它:

keywords <- c(\"knowledge management\", \"gestión del conocimiento\")
npox <- grep(paste(keywords, collapse = \"|\"), full[,c(7)], ignore.case = T)

但是,这不适用于两列或更多列,只有一列full[,c(7)] 任何人都知道我能做什么?
样本数据(csv):https://tempsend.com/rxucj

  • 我不知道您的问题格式是否存在问题,但您可以编辑您的问题以向我们展示您正在使用的代码吗?目前我们不知道您正在搜索什么文本或在哪些列中。谢谢。
  • 完成,列在full[,c(7)] 中指定

标签: r dataframe


【解决方案1】:

不要在单个列上使用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

【讨论】:

  • 这可能是最精明的答案,问题:如果我只想要涉及某些列的结果,我是否只按我需要的列号对结果 df 进行子集化?
  • @Roiadams 看到我的更新
猜你喜欢
  • 1970-01-01
  • 2018-11-08
  • 2018-08-01
  • 1970-01-01
  • 2013-08-09
  • 1970-01-01
  • 2021-10-05
  • 2019-05-04
  • 1970-01-01
相关资源
最近更新 更多