Interpreting “condition has length > 1” warning from `if` function

后端 未结 6 1912
半阙折子戏
半阙折子戏 2020-11-22 10:31

I have an array:

a <- c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0         


        
6条回答
  •  醉梦人生
    2020-11-22 11:16

    if statement is not vectorized. For vectorized if statements you should use ifelse. In your case it is sufficient to write

    w <- function(a){
    if (any(a>0)){
      a/sum(a)
    }
      else 1
    }
    

    or a short vectorised version

    ifelse(a > 0, a/sum(a), 1)
    

    It depends on which do you want to use, because first function gives output vector of length 1 (in else part) and ifelse gives output vector of length equal to length of a.

提交回复
热议问题