R sappy函数返回空值

R sappy函数返回空值,r,function,sapply,R,Function,Sapply,我正在学习一些基本的R编程,做这个精辟的练习给我提出了以下问题,我运行了以下代码,但我无法理解返回空值的原因 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 <- fu

我正在学习一些基本的R编程,做这个精辟的练习给我提出了以下问题,我运行了以下代码,但我无法理解返回空值的原因

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

temp这是
cat
功能的输出:

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

这是
cat
功能的输出:

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

每个函数都必须返回一些东西。正如@MichaelChirico所演示的那样,
cat
在控制台中打印输出并返回
NULL
,这些
NULL
作为输出从
print_info
函数返回

您可以使用
paste
/
paste0,而不是在函数中使用
cat
print

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

print\u info每个函数都必须返回一些内容。正如@MichaelChirico所演示的那样,
cat
在控制台中打印输出并返回
NULL
,这些
NULL
作为输出从
print_info
函数返回

您可以使用
paste
/
paste0,而不是在函数中使用
cat
print

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

print\u info我现在的疑问是,为什么在返回函数体中指定的字符串后会打印它。没有打印功能,当只请求1个列表时,返回2个列表的逻辑是什么?@JavierFernandez这是
print(sappy(.)
的输出,因为您没有为任何内容分配
sappy
,默认情况下,它是通过
print
运行的。如果改为写入
x=sapply(.)
,则不会打印
NULL
。因此发生了两件事:(1)在
sapply
中,运行
cat
,并为
temp
的每个元素生成输出;(2)
print
应用于
sapply
的输出,我现在的疑问是,为什么在返回函数体中指定的字符串后打印它。没有打印功能,当只请求1个列表时,返回2个列表的逻辑是什么?@JavierFernandez这是
print(sappy(.)
的输出,因为您没有为任何内容分配
sappy
,默认情况下,它是通过
print
运行的。如果改为写入
x=sapply(.)
,则不会打印
NULL
。因此发生了两件事:(1)在
sapply
内,运行
cat
并为
temp
的每个元素生成输出;(2)
print
应用于肯定返回预期输出的
sapply
的输出,但是为什么cat函数返回2个输出?@JavierFernandez,因为2个输出与
cat
相关。一个是显示的内容,另一个是返回的内容
平均温度为4.8
是显示的温度,
NULL
是从每个
cat
返回的温度。这肯定会返回预期的输出,但为什么cat函数会返回两个输出?@JavierFernandez,因为两个输出与
cat
相关。一个是显示的内容,另一个是返回的内容
平均温度为4.8
是显示的温度,
NULL
是从每个
cat
返回的温度。