解释从‘if’函数发出的“条件有长度>1”警告我有一个数组: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,如果是,则将每个元素除以总数之和。否则它应该只记录1。我收到以下警告信息: Warning message:
In if (a > 0) { :
the condition has length > 1 and only the first element will be used如何纠正这个函数?
3 回答
慕容708150
TA贡献1831条经验 获得超4个赞
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
ibeautiful
TA贡献1993条经验 获得超5个赞
if
ifelse
w <- function(a){if (any(a>0)){ a/sum(a)} else 1}
ifelse(a > 0, a/sum(a), 1)
ifelse
a
.
POPMUISE
TA贡献1765条经验 获得超5个赞
ifelse
:
(a/sum(a))^(a>0)
a <- c(0, 1, 0, 0, 1, 1, 0, 1)(a/sum(a))^(a>0)[1] 1.00 0.25 1.00 1.00 0.25 0.25 1.00 0.25
- 3 回答
- 0 关注
- 1116 浏览
添加回答
举报
0/150
提交
取消