我有以下问题。
table <- data.frame(col1 = c("cars1 gm", "cars2 gl"), col2 = c("cars1 motor mel", "cars2 prom del"))
col1 col2
1 cars1 gm cars1 motor mel
2 cars2 gl cars2 prom del
table$word <- gsub(table$col1, ' ', table$col2)
Warning message: In gsub(table$col1, " ", table$col2) : argument
'pattern' has length > 1 and only the first element will be used
Run Code Online (Sandbox Code Playgroud)
如何创建一个名为word仅包含col2未出现在 中的值的新列col1?
col1 col2 word
1 cars1 gm cars1 motor mel motor mel
2 cars2 gl cars2 prom del prom del
Run Code Online (Sandbox Code Playgroud)
您可以使用gsub来构建您的查找,然后sapply在列上执行gsub感兴趣的操作:
table$col1 <- gsub(" ", "|", table$col1)
table$word <- sapply(1:nrow(table), function(x) gsub(table$col1[x], "", table$col2[x]))
table
# col1 col2 word
#1 cars1|gm cars1 motor mel motor mel
#2 cars2|gl cars2 prom del prom del
Run Code Online (Sandbox Code Playgroud)
使用与上述答案类似的想法,但使用mapply代替sapply:
table$word <- mapply(function(x, y) gsub( gsub(" ", "|", x), "", y),
table$col1,
table$col2)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16155 次 |
| 最近记录: |