【问题标题】:sapply function returning null valuessapply 函数返回空值
【发布时间】:2020-08-17 15:18:58
【问题描述】:

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

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 值吗?

谢谢你:)

【问题讨论】:

    标签: r function sapply


    【解决方案1】:

    这是cat 函数的输出:

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

    【讨论】:

    • 我现在的疑问是,为什么在返回函数主体中指定的字符串后打印出来。没有打印功能,只请求1个列表,返回2个列表的逻辑是什么?
    • @JavierFernandez 它是print(sapply(.)) 的输出,因为您没有将sapply 分配给任何东西,默认情况下它通过print 运行。如果您改为写x = sapply(.),则不会打印NULL。因此发生了两件事:(1)在sapply 内,cat 运行并为temp 的每个元素生成输出(2)print 应用于sapply 的输出
    【解决方案2】:

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

    您可以在函数中使用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
    

    【讨论】:

    • 那肯定会返回预期的输出,但是为什么用cat函数返回2个输出呢?
    • @JavierFernandez 因为 2 个输出与 cat 相关联。一个是显示的内容,另一个是返回的内容。 The average temperature is 4.8 是显示的内容,NULL 是每个 cat 返回的内容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多