【问题标题】:How to check if some categorical variables are within a column in R?如何检查某些分类变量是否在 R 的列中?
【发布时间】:2022-10-17 13:26:51
【问题描述】:

我正在尝试编写一个if statement 来检查一个或另一个分类变量是否在我的数据框中的列中。因此,我使用%in%。当我有 1 个变量时,它工作得很好:

if("setosa" %in% iris$Species){
  print("hi")
}
[1] "hi"

但是如果我有条件OR,我就不能使用它。

# it should return TRUE because "setosa" is within the column Species
if(("setosa" | "new") %in% iris$Species){
  print("hi")
}

Error in "setosa" | "virginica" : 
  operations are possible only for numeric, logical or complex types

有谁知道该怎么做,或者我是否可以使用另一个函数来检查我的 if statement 是 TRUE 还是 FALSE?

提前致谢

【问题讨论】:

  • any(c("setosa","new") %in% iris$Species)
  • @pluke c("setosa","new") 给了我这个错误:Error in if (c("setosa", "new") %in% iris$Species) { : the condition has length > 1 但是如果我像@user2974951 所说的那样使用any,它就可以工作。非常感谢!

标签: r if-statement


【解决方案1】:

将条件放入向量中并检查是否有任何为真(对于 OR,使用 all 表示 AND)any(c("setosa","new") %in% iris$Species)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-26
    • 2016-12-28
    • 1970-01-01
    • 2012-02-05
    • 2012-04-03
    • 2016-08-21
    相关资源
    最近更新 更多