【问题标题】:How to write an if else statement in R when the condition has a length greater than 1当条件长度大于1时如何在R中编写if else语句
【发布时间】:2020-02-06 22:26:41
【问题描述】:

我正在尝试在 R 的 for 循环中编写 if else 语句,如果 i == 向量中的任何值范围,则执行此操作,否则,执行其他操作。我知道当 if 语句中的条件的长度大于 1 时,只使用第一个值,但是,我想知道是否有办法解决这个问题,因为我使用的向量非常长(180 个值)并且为向量中的每个条件编写单独的 if 语句会非常混乱。我正在尝试完成的一个示例在下面输入。有没有办法只使用条件中的第一个值?

    example<-c(1,2,3,4)
    z<-c()
    for (i in 1:10)
    {
      if (i==example) #if i == any of the values in example
      {
        z<-c(z,0) #add a 0 to the vector z
      }else {z<-c(z,1)} #else add a 1
    }

    #resulting vector should have four zeros and six ones

【问题讨论】:

  • 尝试使用%in% 运算符。即if (i %in% example)

标签: r if-statement


【解决方案1】:

您使用循环使事情变得更加困难:

x <- 1:10
example <- 1:4
(z <- ifelse(x %in% example, 0, 1))
#  [1] 0 0 0 0 1 1 1 1 1 1

【讨论】:

  • 对于我构建循环的实际代码是必要的,这里提供的示例只是为了证明我需要一种方法来覆盖“条件大于长度 1”警告。 %in% 运算符完美运行。不过,我感谢您的意见。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-29
  • 1970-01-01
  • 2023-03-24
  • 1970-01-01
  • 2014-09-06
  • 1970-01-01
相关资源
最近更新 更多