Search code examples
rnumericaddition

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!


Solution

  • 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