Why is my function returning me NULL?

Hi all,

I would like a little help with this code. So I basically need to create a function where I sum three vectors until the length of the shortest one. My problem is the following:
Whenever the sum is made with v4(NULL) the function returns me NULL instead of "numeric(0)" and when I sum v2,v3 and v5 the function also returns me NULL (which is strange since these three vectors contain values).

v1 <- as.integer(seq(1,30, length.out = 10)) 
v2 <- c(13:16, NA, NA, 14, NA)
v3 <- c(rep(1,times=5),4,5,23,NA,NA)          
v4 <- NULL
v5 <- rev(v1)                 

sum_3_vectors_tillshortest <- function(vet1,vet2,vet3){ 
  vresult <- NULL

  len_vet1 <- length(vet1)
  len_vet2 <- length(vet2)
  len_vet3 <- length(vet3)
  
  if(len_vet1 < len_vet2 && len_vet1 < len_vet3){
    le <- len_vet1
  }else{
    if (len_vet2 < len_vet3){
      le <- len_vet2
    }else{
      le <- len_vet3
    }
    
    for (i in 1:le){
      vresult[i] <- vet1[i] + vet2[i] + vet3[i]
    }
  }
return(vresult)
}

Hi there,

I am happy to help you if you can make it clear what output you're expecting to get.

In short, NULL will differ from case to case depending on what code you use and how it needs to work. To have v4 as a scalar or single length vector is already not great. Similarly, it is not the same as 0 so to speak. Also, functions don't use it in the same way:

identical(4 + NULL,sum(4,NULL))
#> [1] FALSE

Created on 2021-07-12 by the reprex package (v2.0.0)

Also, having different lengths, such as v2 being a length of 8 vs 10 vs the others will also have other implications. The best is to simplify the problem into its components and then to address each one separately.

Is this what you expect?

v1 <- as.integer(seq(1,30, length.out = 10)) 
v2 <- c(13:16, NA, NA, 14, NA)
v3 <- c(rep(1,times=5),4,5,23,NA,NA)          
v4 <- NULL
v5 <- rev(v1)

vecSum <- function(vec1, vec2, vec3){
  m <- min(length(vec1), length(vec2), length(vec3))
  head(vec1, m) + head(vec2, m) + head(vec3, m)
}

vecSum(v1, v2, v3)
#> [1] 15 19 23 27 NA NA 39 NA
vecSum(v3, v4, v5)
#> numeric(0)

Created on 2021-07-12 by the reprex package (v2.0.0)

Yes! These are exactly the outputs I was looking for :slight_smile:

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.