【问题标题】:conditional removing from a vector without if statement in R [duplicate]在R中没有if语句的情况下有条件地从向量中删除[重复]
【发布时间】:2020-02-08 12:47:44
【问题描述】:

如果不使用if 语句,是否可以从字符向量中删除"out"(例如a1)并且如果向量中不存在"out"(例如a2)只返回向量本身?

a1 = c("out", "bagh", "bir")
a2 = c("bagh", "bir")

 a1[-which("out" %in% a1)]

 a2[-which("out" %in% a2)]

【问题讨论】:

标签: r function dataframe if-statement vector


【解决方案1】:

使用setdiff

setdiff(a1, "out")
#[1] "bagh" "bir" 

setdiff(a2, "out")
#[1] "bagh" "bir" 

如果我们不使用which%in% 也可以工作

a1[!a1 %in% "out"]
a2[!a2 %in% "out"]

【讨论】:

【解决方案2】:

而且也非常R-ish:

a1[a1 != "out"]

选择所有不等于“out”的向量元素。

【讨论】:

    猜你喜欢
    • 2013-03-27
    • 1970-01-01
    • 2017-10-11
    • 2023-03-20
    • 2018-10-25
    • 2020-08-08
    • 2020-02-03
    • 2012-06-05
    • 2021-11-04
    相关资源
    最近更新 更多