1

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

3 Answers 3

4

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 ------------------------------ 
Sign up to request clarification or add additional context in comments.

Comments

4

In describe(), the last expression is cat("\n------------------------------\n"), which returns NULL as cat() returns NULL invisibly

You can 1) Use walk() instead of map()

  1. add invisible() after cat("\n------------------------------\n")

  2. add return(s) in describe()

Comments

0

This is uncommon. However, I recommend using vanilla R.

describe = \(v) { m = varlabs$label[varlabs$variable==v] cat("Describing variable", m, "\n\n") print(summary(toy[v])) cat("\n------------------------------\n") } # > and how to suppress the additional output. lapply(names(toy), describe) |> invisible() 
Describing variable Var 1 V1 Min. :-1.59126 1st Qu.:-0.82428 Median :-0.08884 Mean :-0.07803 3rd Qu.: 0.67716 Max. : 1.38914 ------------------------------ Describing variable Var 2 V2 Min. :-1.4352 1st Qu.:-0.6911 Median : 0.2112 Mean : 0.1723 3rd Qu.: 0.8825 Max. : 1.7645 ------------------------------ 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.