解释“条件的长度为> 1"来自if函数的警告

问题描述:

我有一个数组:

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, 0, 1, 1, 0, 0, 1, 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, 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, 0, 0, 0, 0)

,并希望实现以下功能:

and would like to implement the following function:

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

此功能想检查a中是否有大于0的值,如果是,则将每个元素除以总和.

This function would like to check whether there is any value in a larger than 0 and if yes then divide each element by the sum of the total.

否则,它应该只记录1.

Otherwise it should just record 1.

我收到以下警告消息:

 Warning message:
 In if (a > 0) { :
 the condition has length > 1 and only the first element will be used

如何纠正该功能?

也许您想要ifelse:

a <- c(1,1,1,1,0,0,0,0,2,2)
ifelse(a>0,a/sum(a),1)

 [1] 0.125 0.125 0.125 0.125 1.000 1.000 1.000 1.000
 [9] 0.250 0.250