代码之家  ›  专栏  ›  技术社区  ›  cnauber

如何使if返回期望的结果(R)?

  •  0
  • cnauber  · 技术社区  · 5 年前

    关于如何解决这个错误有什么想法吗?

    Warning messages:
    1: In if (A <0) {:
       the condition has length> 1 and only the first element will be used
    2: In if (A> 0) {:
       the condition has length> 1 and only the first element will be used
    
    A <- c (0, -2, -4,1,5)
    B <- if (A <0) {A/-2} else if (A> 0) {A/2} else {A = 0}
    

    B的结果必须是(0,1,2,0,5,2.5)。

    1 回复  |  直到 5 年前
        1
  •  1
  •   Ronak Shah    5 年前

    你的问题的答案是使用 ifelse if . 如果不是 用于向量 如果 / else

    A <- c (0, -2, -4,1,5)
    ifelse(A < 0, A/-2, ifelse(A> 0,  A/2, 0))
    #[1] 0.0 1.0 2.0 0.5 2.5
    

    如果不是

    abs(A/2)
    #[1] 0.0 1.0 2.0 0.5 2.5