如何通过另一个字符串向量中的元素删除字符串向量中的元素

时间:2017-02-05 07:27:19

标签: r set-difference

setdiff(c("a","c"),c("a","b","c","d"))
 #character(0)

这段代码应该返回c的向量(" b"," d"),它有什么问题?

1 个答案:

答案 0 :(得分:2)

setdiff是不对称的,因为帮助页面警告(虽然巧妙)。

这可以按预期工作,

> setdiff(c("a","b","c","d"),c("a","c"))
[1] "b" "d"

一个简单的函数可以正常工作,

setdiff2 <- function(x,y){
  d1 <- setdiff(x,y)
  d2 <- setdiff(y,x)
  if(length(d2) > length(d1))
    return(d2)
  else
    return(d1)
}

> setdiff2(c("a","c"), c("a","b","c","d"))
[1] "b" "d"