涉及 numeric(0) 值的加法 [英] Addition involving numeric(0) values

查看:67
本文介绍了涉及 numeric(0) 值的加法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设 x 是一个实数或向量.我是有价值的-假.然后 x[i] 将返回 numeric(0).我想把它当作一个实数 0 或整数 0,它们都适合加法.

Suppose x is a real number, or a vector. i is valued-False. Then x[i] will return numeric(0). I would like to treat this as a real number 0, or integer 0, which are both fit for addition.

numeric(0) 添加到任何实数将返回 numeric(0),而我希望获得添加的实数作为结果.我该怎么做才能转换数字 (0) 值?提前致谢!

numeric(0) added to any real number will return numeric(0), whereas I wish to obtain the real number being added as the result. What can I do to convert the numeric (0) value? Thanks in advance!

推荐答案

只有当我们做+时,才出现问题.如果我们使用 sum

It is only when we do the +, it is a problem. This can be avoided if we use sum

sum(numeric(0), 5)
#[1] 5
sum(numeric(0), 5, 10)
#[1] 15

或者如果我们需要使用+,一个简单的选择是与0连接,选择第一个元素.如果元素是numeric(0),则替换为0,对于其他情况,第一个元素保持不变

Or if we need to use +, an easy option is to concatenate with 0, select the first element. If the element is numeric(0), that gets replaced by 0, for other cases, the first element remain intact

c(numeric(0), 0)[1]
#[1] 0

使用一个小例子

lst1 <- list(1, 3, numeric(0),  4, numeric(0))
out <- 0
for(i in seq_along(lst1)) {
       out <- out + c(lst1[[i]], 0)[1]
  }

out
#[1] 8

这篇关于涉及 numeric(0) 值的加法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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