Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (50.2k points)
edited by

I am running the following code but I cannot understand the logic why the NULL values are returned.

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 me understand why am I getting these NULL values?

1 Answer

0 votes
by (108k points)

See the bellow example: 

x = cat('hi\n')

# hi

print(x)

# NULL

With the help of the above example, what I am trying to tell you is that in R programming, every function has to return something. The 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

Browse Categories

...