将单词(字符)与R中的参考值匹配
这是我的数据(a) 另外,这是另一个数据(B)。这是一个参考数据将单词(字符)与R中的参考值匹配,r,character,matching,R,Character,Matching,这是我的数据(a) 另外,这是另一个数据(B)。这是一个参考数据 keyword value [1] shoes 1 [2] shirts 2 ... 我需要匹配这个数据集 所以,我想知道结果 keyword vlaue [1] shoes 1 [2] childrenshoes 1 (because, this keyword include the 'shoes') [3] nikeshoes 1 (be
keyword value
[1] shoes 1
[2] shirts 2
...
我需要匹配这个数据集
所以,我想知道结果
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
...
如果使用“合并”,则与此数据集不匹配。这是因为数据(B)中的关键字与数据(A)中的数据不完全匹配
我可以使用regexpr()或gregexpr()逐个处理这个问题。
然而,我在数据(B)中有很多参考资料
那么,我该如何处理这个问题呢 这里有一种方法:
首先,您的数据:
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))
一个有趣的问题。一定要确保在将来,您以一种便于站点上其他人在试验前复制和粘贴的方式共享示例数据。
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))
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