应用函数返回空值

sapply function returning null values

我正在学习一些基本的 R 编程,并且在做这个应用练习时提出了以下问题,我 运行 下面的代码,但我无法理解 NULL 值是 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

你能帮我理解为什么我得到这个 NULL 值吗?

谢谢:)

这是 cat 函数的输出:

x = cat('hi\n')
# hi
print(x)
# NULL

每个功能都必须 return 一些东西。正如@MichaelChirico 所证明的,cat 在控制台和 returns NULL 中打印输出,那些 NULL 被 returned 作为 [=14= 的输出] 功能。

您可以在函数中使用 paste/paste0

而不是在函数中使用 catprint
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