Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Addition involving numeric(0) values

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!

like image 770
siegfried Avatar asked Jun 09 '26 22:06

siegfried


1 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
like image 62
akrun Avatar answered Jun 11 '26 10:06

akrun