Addition involving numeric(0) values

前端 未结 2 898
礼貌的吻别
礼貌的吻别 2021-01-21 01:33

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

2条回答
  •  遇见更好的自我
    2021-01-21 01:53

    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
    

提交回复
热议问题