Addition involving numeric(0) values

随声附和 提交于 2021-01-20 07:06:10

问题


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) 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!


回答1:


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

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

Using a small example

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



回答2:


You can use max/min with 0 to get 0 as output when input is numeric(0).

x <- 1:10
max(x[FALSE], 0)
#[1] 0

min(x[FALSE], 0)
#[1] 0


来源:https://stackoverflow.com/questions/64236145/addition-involving-numeric0-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!