Search code examples
rfunctionsapply

sapply function returning null values


I'm studying some basic R programming and doing this sapply exercise raise me the following question, I run the following code but I cannot understand the reason why the NULL values are return.

temp <- list(c(3,7,9,6,-1),
         c(6,9,12,13,5),
         c(4,8,3,-1,-3),
         c(1,4,7,2,-2),
         c(5,7,9,4,2),
         c(-3,5,8,9,4),
         c(3,6,9,4,1))

print_info <- function(x) {
  cat("The average temperature is", mean(x), "\n")
}

sapply(temp, print_info)

The average temperature is 4.8 
The average temperature is 9 
The average temperature is 2.2 
The average temperature is 2.4 
The average temperature is 5.4 
The average temperature is 4.6 
The average temperature is 4.6 
NULL
NULL
NULL
NULL
NULL
NULL
NULL

Can you help understand why I get this NULL values?

Thank you :)


Solution

  • Every function has to return something. As demonstrated by @MichaelChirico that cat prints the output in the console and returns NULL, those NULL are returned as output from print_info function.

    Instead of using cat or print in the function, you could use paste/paste0

    print_info <- function(x) {
      paste0("\nThe average temperature is ", mean(x))
    }
    
    cat(sapply(temp, print_info))
    
    #The average temperature is 4.8 
    #The average temperature is 9 
    #The average temperature is 2.2 
    #The average temperature is 2.4 
    #The average temperature is 5.4 
    #The average temperature is 4.6 
    #The average temperature is 4.6