假设我有一个随机名称的字符向量。我还有另一个带有许多汽车品牌的角色矢量,我想删除原始矢量中发生的汽车事故。
所以给出了矢量:
dat = c("Tonyhonda","DaveFord","Alextoyota")
car = c("Honda","Ford","Toyota","honda","ford","toyota")
我希望最终得到如下内容:
dat = c("Tony","Dave","Alex")
如何删除R?
中的部分字符串答案 0 :(得分:16)
gsub(x = dat, pattern = paste(car, collapse = "|"), replacement = "")
[1] "Tony" "Dave" "Alex"
答案 1 :(得分:1)
刚刚将上述42条评论正式化。而不是使用
car = c("Honda","Ford","Toyota","honda","ford","toyota")
你可以使用:
carlist = c("Honda","Ford","Toyota")
gsub(x = dat, pattern = paste(car, collapse = "|"), replacement = "", ignore.case = TRUE)
[1] "Tony" "Dave" "Alex"
这样,您只需将要排除的每个单词放在列表中一次。