How to name the columns of map_dfc() in R?

Viewed 1382

I have a question with regard to naming the columns that come out of the purrr (Tidyverse) map_dfc function.

I have a function that outputs a single number, let's say this function is rnorm(). I would like to replicate this function n = 10 times with different values for the mean and save the output to a dataframe, with the column names being the names of the mean.

library(purrr)
f_replicates <- function(n){
  replicate(n=10, rnorm(n=1, mean = n))
}

map_dfc(c(4, 10, 20), f_replicates)

This creates a tibble, where the column names are set to

New names:

  • NA -> ...1
  • NA -> ...2
  • NA -> ...3

Question

How do you create a dataframe with the means as column names?

1 Answers

If you want to use map_dfc you need named output. You can name the output either inside f_replicates function or after calling map_dfc.

f_replicates <- function(n){
  setNames(data.frame(replicate(n=10, rnorm(n=1, mean = n))), paste0('mean_', n))
}

purrr::map_dfc(c(4, 10, 20), f_replicates)

#     mean_4   mean_10  mean_20
#1  6.058674 10.403541 18.76108
#2  4.871537  7.659355 20.11602
#3  3.654629 11.274651 19.90208
#4  3.848754  9.033448 20.22821
#5  4.788205  9.135202 19.80254
#6  4.035633  9.637215 20.27024
#7  3.748321 10.521144 19.55705
#8  1.927361 10.364091 20.95778
#9  3.857333  9.998084 21.17971
#10 2.490418 11.254264 20.32196
Related