安全、优雅地从向量中删除特定元素
我想从向量中排除指定列表中的元素,即删除出现在排除列表中的该向量的元素。
我不知道元素是否已经丢失,因此通过 -which(v %in% excepts)
删除元素(如下所示)会导致整个向量在它们未出现的情况下被清除那个向量。
我怎样才能以安全且优雅的方式做到这一点?我是否必须使用布尔(逻辑
)掩码,或者是否有我缺少的更优雅的方式?
v <- c("things", "sometimes", "go", "awry", "quickly")
excludes <- c("sometimes", "quickly")
v <- v[-which(v %in% excludes)]
v
# "things" "go" "awry"
which(v %in% excludes)
# Here `excludes` has already been removed, so v is cleared
v <- v[-which(v %in% excludes)]
v
# character(0)
布尔掩码方法
v <- c("things", "sometimes", "go", "awry", "quickly")
excludes <- c("sometimes", "quickly")
v <- v[!v %in% excludes]
v <- v[!v %in% excludes] # perform the removal a second time
v # contains desired value
# "things" "go" "awry"
I would like to exclude elements in a specified list from a vector, i.e. remove elements of that vector which appear in the exclusion list.
I don't know if the elements are already missing, so dropping elements via -which(v %in% excludes)
as below causes the entire vector to be cleared in the case that they do not appear in that vector.
How can I do this in a safe and elegant way? Should I necessarily use a boolean (logical
) mask or is there a more elegant way I am missing?
v <- c("things", "sometimes", "go", "awry", "quickly")
excludes <- c("sometimes", "quickly")
v <- v[-which(v %in% excludes)]
v
# "things" "go" "awry"
which(v %in% excludes)
# Here `excludes` has already been removed, so v is cleared
v <- v[-which(v %in% excludes)]
v
# character(0)
Boolean mask approach
v <- c("things", "sometimes", "go", "awry", "quickly")
excludes <- c("sometimes", "quickly")
v <- v[!v %in% excludes]
v <- v[!v %in% excludes] # perform the removal a second time
v # contains desired value
# "things" "go" "awry"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果没有重复项,请使用
setdiff
或对于重复项,使用
vsetdiff
If there are no duplicates, use
setdiff
Or with duplicates,
vsetdiff