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