Search code examples
rpurrr

Change output of the `purrr::map` function


I have this small function and want to apply it to a dataset using purrr::map(). It does what I expect it to do, but after the output it also prints a list of NULL, which I don't want. I would like to understand why this happens and how to suppress the additional output.

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

Created on 2025-03-08 with reprex v2.1.0


Solution

  • You can use walk(), which is map() with the return value suppressed by invisible().

    purrr::walk(names(toy), describe)
    
    Describing variable Var 1 
    
       Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
    -1.5025 -0.1849  0.4309  0.2586  0.8135  1.3003 
    
    ------------------------------
    Describing variable Var 2 
    
        Min.  1st Qu.   Median     Mean  3rd Qu.     Max. 
    -0.51539  0.05476  0.19852  0.37863  0.78792  1.28135 
    
    ------------------------------