安全、优雅地从向量中删除特定元素

发布于 2025-01-11 16:46:57 字数 898 浏览 0 评论 0原文

我想从向量中排除指定列表中的元素,即删除出现在排除列表中的该向量的元素。

我不知道元素是否已经丢失,因此通过 -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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

失与倦" 2025-01-18 16:46:57

如果没有重复项,请使用 setdiff

setdiff(v, excludes)
[1] "things" "go"     "awry"  

或对于重复项,使用 vsetdiff

library(vecsets)
vsetdiff(v, excludes)

If there are no duplicates, use setdiff

setdiff(v, excludes)
[1] "things" "go"     "awry"  

Or with duplicates, vsetdiff

library(vecsets)
vsetdiff(v, excludes)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文