解释“条件具有长度"1"来自`if`函数的警告 [英] Interpreting "condition has length > 1" warning from `if` function

查看:28
本文介绍了解释“条件具有长度"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)

并希望实现以下功能:

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

这篇关于解释“条件具有长度"1"来自`if`函数的警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆