While playing around with the purrr
package of the Tidyverse in R
, I saw that the map()
function returns a list.
library(tidyverse)
set.seed(123)
map(1:5, ~rnorm(3))
#> [[1]]
#> [1] -0.5604756 -0.2301775 1.5587083
#>
#> [[2]]
#> [1] 0.07050839 0.12928774 1.71506499
#>
#> [[3]]
#> [1] 0.4609162 -1.2650612 -0.6868529
#> ......
I want to convert this list to a data frame with 3 columns. One option would be using do.call(rbind, .)
. However, I also noticed that the map_dfr()
function existed.
Using this function in the same way as the map()
provides an error.
map_dfr(1:5, ~rnorm(3))
#> Error: Argument 1 must have names.
Question
What are the differences between the map()
and the map_dfr()
functions that lead to this error? And how should you use the map_dfr()
function to bind the rows directly in the mapping function?
t(mapply(rnorm, 3, 1:5))
– Salpiglossismap_dfr
answer - https://mcmap.net/q/1164854/-loop-through-function-and-stack-the-output-into-a-dataset-in-r/10276092 – Parget