![](/img/trans.png)
[英]Use gsub to remove pattern from a string: argument 'pattern' has length > 1 and only the first element will be used
[英]argument 'pattern' has length > 1 and only the first element will be used - GSUB()
我有以下问题。
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
如何创建一个名为word
的新列,该列仅包含col2
未出现在col1
那些值?
col1 col2 word
1 cars1 gm cars1 motor mel motor mel
2 cars2 gl cars2 prom del prom del
您可以使用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
使用与上述答案类似的想法,但使用mapply
而不是sapply
:
table$word <- mapply(function(x, y) gsub( gsub(" ", "|", x), "", y),
table$col1,
table$col2)
您可以使用mapply
,
#Make sure you read your data with stringsAsFactors = FALSE,
table<-data.frame(col1=c("cars1 gm","cars2 gl"),
col2=c("cars1 motor mel", "cars2 prom del"), stringsAsFactors = FALSE)
table$word <- mapply(function(x, y)
trimws(gsub(sapply(strsplit(x, ' '), paste, collapse = '|'), '', y)),
table$col1, table$col2)
table
# col1 col2 word
#1 cars1 gm cars1 motor mel motor mel
#2 cars2 gl cars2 prom del prom del
您可以像这样使用mapply
、 paste
和strsplit
。
table$word <- mapply(function(x, y) paste(y[!(y %in% x)], collapse=" "),
strsplit(as.character(table$col1), split=" "),
strsplit(as.character(table$col2), split=" "))
这里, strsplit
在 " " 上拆分字符向量并返回一个列表。 这两个列表被提供给mapply
,它检查每个列表的相应值并返回第二个列表中不在第一个列表中的值。 结果向量与paste
及其折叠参数粘贴在一起。
返回
table
col1 col2 word
1 cars1 gm cars1 motor mel motor mel
2 cars2 gl cars2 prom del prom del
您可以拆分col1
和col2
的字符串,因为单词的顺序可能不同,然后您可以使用setdiff
选择仅出现在col2
中的setdiff
:
table$word=sapply(1:nrow(table),function(i)
paste(setdiff(unlist(strsplit(table$col2[i]," ")),
unlist(strsplit(table$col1[i]," "))),collapse=" "))
这将返回:
col1 col2 word
1 cars1 gm cars1 motor mel motor mel
2 cars2 gl cars2 prom del prom del
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.