简体   繁体   English

在 R 中跨字符向量查找匹配项

[英]Finding Matches Across Char Vectors in R

Given the below two vectors is there a way to produce the desired data frame?鉴于以下两个向量,有没有办法生成所需的数据帧? This represents a real world situation which I have to data frames the first contains a col with database values (keys) and the second contains a col of 1000+ rows each a file name (potentials) which I need to match.这代表了一个现实世界的情况,我必须数据帧第一个包含一个带有数据库值(键)的列,第二个包含一个包含 1000+ 行的列,每个文件名(可能)我需要匹配。 The problem is there can be multiple files (potentials) matched to any given key.问题是可以有多个文件(可能)与任何给定的键匹配。 I have worked with grep, merge, inner join etc. but was unable to incorporate them into one solution.我曾使用过 grep、合并、内部连接等,但无法将它们合并到一个解决方案中。 Any advise is appreciated!任何建议表示赞赏!

potentials <- c("tigerINTHENIGHT",
            "tigerWALKINGALONE",
            "bearOHMY",
            "bearWITHME",
            "rat",
            "imatchnothing")
keys <- c("tiger",
            "bear",
            "rat")


desired <- data.frame(keys, c("tigerINTHENIGHT, tigerWALKINGALONE", "bearOHMY, bearWITHME", "rat"))
names(desired) <- c("key", "matches")

Psudo code for what I think of as the solution:我认为的解决方案的伪代码:

#new column which is comma separated potentials
# x being the substring length i.e. x = 4 means true if first 4 letters match
function createNewColumn(keys, potentials, x){
  str result = na
  foreach(key in keys){
    if(substring(key, 0, x) == any(substring(potentals, 0 ,x))){ //search entire potential vector
      result += potential that matched + ', '
    }
  }
  return new column with result as the value on the current row
}

We can write a small functions to extract matches and then loop over the keys:我们可以编写一个小函数来提取匹配项,然后遍历键:

return_matches <- function(keys, potentials, fixed = TRUE) {
  vapply(keys, function(k) {
    paste(grep(k, potentials, value = TRUE, fixed = fixed), collapse = ", ")
  }, FUN.VALUE = character(1))
}

vapply is just a typesafe version of sapply meaning it will never return anything but a character vector. vapply只是sapply的类型安全版本,这意味着它只会返回字符向量。 When you set fixed = TRUE the function will run a lot faster but does not recognise regular expressions anymore.当您设置fixed = TRUE时,function 将运行得更快,但不再识别正则表达式。 Then we can easily make the desired data.frame :然后我们可以轻松制作所需的data.frame

df <- data.frame(
  key = keys,
  matches = return_matches(keys, potentials),
  stringsAsFactors = FALSE
)
df
#>         key                            matches
#> tiger tiger tigerINTHENIGHT, tigerWALKINGALONE
#> bear   bear               bearOHMY, bearWITHME
#> rat     rat                                rat

The reason for putting the loop in a function instead of running it directly is just to make the code look cleaner.将循环放在 function 中而不是直接运行它的原因只是为了使代码看起来更干净。

You can interate using grep您可以使用grep进行交互

 > Match <- sapply(keys, function(item) {
                  paste0(grep(item, potentials, value = TRUE), collapse = ", ")
     } )     

> data.frame(keys, Match, row.names = NULL)
       keys                              Match
    1 tiger tigerINTHENIGHT, tigerWALKINGALONE
    2  bear               bearOHMY, bearWITHME
    3   rat                                rat

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM