将wordss(字符)与R中的参考值匹配

kma*_*gyo 2 r character matching

这是我的数据(A).

    keyword
[1] shoes
[2] childrenshoes
[3] nikeshoes
[4] sportsshiirts
[5] nikeshirts
[6] shirts
...
Run Code Online (Sandbox Code Playgroud)

另外,这是另一个数据(B).它是参考数据.

   keyword  value
[1] shoes    1
[2] shirts   2
...
Run Code Online (Sandbox Code Playgroud)

我需要匹配这个数据集.

所以,我想要那个结果.

    keyword        vlaue
[1] shoes          1
[2] childrenshoes  1     (because, this keyword include the 'shoes')
[3] nikeshoes      1     (because, this keyword include the 'shoes')
[4] sportsshiirts  2     (because, this keyword include the 'shirts')
[5] nikeshirts     2     (because, this keyword include the 'shirts')
[6] shirts         2
...
Run Code Online (Sandbox Code Playgroud)

如果我使用'merge',我的colud与这个数据集不匹配.这是因为数据(B)中的关键字与数据(A)中的数据不完全匹配.

我可以使用regexpr()或gregexpr()逐个处理.但是,我在数据中有很多参考(B)

那么,我该如何处理这个问题呢?

A5C*_*2T1 6

这是一种方法:

首先,您的数据:

temp <- c("shoes", "childrenshoes", "nikeshoes", 
          "sportsshiirts", "nikeshirts", "shirts")

matchme <- structure(list(keyword = c("shoes", "shirts"), value = 1:2), 
                     .Names = c("keyword", "value"), 
                     class = "data.frame", row.names = c(NA, -2L))
Run Code Online (Sandbox Code Playgroud)

二,输出,一气呵成:

data.frame(
  keyword = temp, 
  value = rowSums(sapply(seq_along(matchme[[1]]), function(x) {
    temp[grepl(matchme[x, 1], temp)] <- matchme[x, 2]
    suppressWarnings(as.numeric(temp))
  }), na.rm = TRUE))
#         keyword value
# 1         shoes     1
# 2 childrenshoes     1
# 3     nikeshoes     1
# 4 sportsshiirts     0
# 5    nikeshirts     2
# 6        shirts     2
Run Code Online (Sandbox Code Playgroud)

grepl执行"matchme"中每个元素data.frame与源"temp"的逻辑匹配data.frame.如果找到匹配项,则从"matchme"的"value"列中提取值data.frame.否则,它保持原始值.这没关系,因为我们知道当我们使用得到的矢量转换时as.numeric,任何不能被强制转换为数字的东西都会变成NA.

在该sapply步骤中,您将获得一个矩阵.如果我们可以假设,将有永远只能是每个项目一个比赛,那么我们就可以放心地使用rowSums的说法na.rm = TRUE"崩溃"的是矩阵分解成可以与我们的"温度"数据相结合,以创建产生的单一载体data.frame.

suppressWarnings在那里添加了一个,因为我知道我会收到很多NAs introduced by coercion警告,不告诉我任何我不知道的事情.

请注意0"sportsshiirts".如果您需要近似匹配,您可能需要查看agrep并查看是否可以修改此方法.