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

后端 未结 6 1920
半阙折子戏
半阙折子戏 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:33

    The way I cam across this question was when I tried doing something similar where I was defining a function and it was being called with the array like others pointed out

    You could do something like this however for this scenarios its less elegant compared to Sven's method.

    sapply(a, function(x) afunc(x))
    
    afunc<-function(a){
      if (a>0){
        a/sum(a)
      }
      else 1
    }
    

提交回复
热议问题