purrr::map执行自定义函数后输出NULL列表的原因及解决方法
问题:使用purrr::map执行自定义函数后出现多余NULL列表输出
我写了一个自定义R函数,想用purrr::map应用到数据集上,函数功能正常,但执行后会额外打印一个含NULL的列表,这不是我想要的。代码和输出如下:
toy <- data.frame(V1 = rnorm(10), V2 = rnorm(10)) varlabs <- data.frame(variable = c("V1", "V2"), label = c("Var 1", "Var 2")) describe <- function(x) { require(dplyr) require(ggplot2) lab <- filter(varlabs, variable == x) |> pull(label) s <- summary(toy[, x]) cat("Describing variable", lab, "\n\n") print(s) cat("\n------------------------------\n") } purrr::map(names(toy), describe)
执行输出:
#> Loading required package: dplyr #> #> Attaching package: 'dplyr' #> The following objects are masked from 'package:stats': #> #> filter, lag #> The following objects are masked from 'package:base': #> #> intersect, setdiff, setequal, union #> Loading required package: ggplot2 #> Describing variable Var 1 #> #> Min. 1st Qu. Median Mean 3rd Qu. Max. #> -0.9447 -0.3762 0.3521 0.2463 0.9040 1.3298 #> #> ------------------------------ #> Describing variable Var 2 #> #> Min. 1st Qu. Median Mean 3rd Qu. Max. #> -1.5429 -1.0039 -0.6099 -0.5736 -0.2366 0.4436 #> #> ------------------------------ #> [[1]] #> NULL #> #> [[2]] #> NULL
原因分析
purrr::map的本质是收集每个函数调用的返回值,生成一个列表。- 你的
describe函数里只有cat、print这类输出操作,没有明确指定返回值。R中函数默认返回最后一行代码的结果,而cat的返回值是NULL,所以每次调用describe都会返回NULL,map就把这些NULL打包成列表输出了。
解决方法
有两种简单的方式消除这个多余输出:
方法1:用purrr::walk替代map
walk是专门用来执行**只产生副作用(比如打印、绘图)**的函数,它不会返回任何结果,自然就不会输出那个NULL列表:
purrr::walk(names(toy), describe)
方法2:用invisible()抑制map的输出
如果一定要用map,可以把map的调用包裹在invisible()里,让返回的NULL列表不被打印出来:
invisible(purrr::map(names(toy), describe))
额外优化建议
把require(dplyr)和require(ggplot2)移到函数外面,避免每次调用函数都重复加载包,优化后的完整代码:
library(dplyr) library(ggplot2) toy <- data.frame(V1 = rnorm(10), V2 = rnorm(10)) varlabs <- data.frame(variable = c("V1", "V2"), label = c("Var 1", "Var 2")) describe <- function(x) { lab <- filter(varlabs, variable == x) |> pull(label) s <- summary(toy[, x]) cat("Describing variable", lab, "\n\n") print(s) cat("\n------------------------------\n") } # 使用walk执行 purrr::walk(names(toy), describe)
内容的提问来源于stack exchange,提问作者Claudio
相关产品推荐
相关产品推荐

