Addition involving numeric(0) values

Viewed 592

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!

2 Answers

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

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
Related