Marcelo Avila
Marcelo Avila

Reputation: 2374

{purrr}: how to replace a simple loop with `purrr::map()` while using up all arguments of a function?

Hi all, I've read the help file and quite a few questions on the topic here but couldn't find an answer. I believe it is a very simple question, so I am likely missing something obvious.

I would like to replace such a basic for loop implementation, such as

lst <- list()
for (i in 1:10) {
  lst[[i]] <- rnorm(n = 3, mean = 5, sd = 3)
}
lst

with purrr::map(), while using up all arguments of the function (here: rnorm())

The following doesn't work and returns an unused argument error.

1:10 %>%
  map(rnorm, n = 3, mean = 5, sd = 3)
# Error in .f(.x[[i]], ...) : unused argument (.x[[i]])

The following runs, but map passed the arguments 1:10 to rnorm(sd = .x), so the result is not what expected.

library(purrr)
1:3 %>% 
  map(rnorm, n = 3, mean = 5)
#> [[1]]
#> [1] 5.133702 6.456135 5.041438
#> 
#> [[2]]
#> [1] 5.722486 4.614772 2.640809
#> 
#> [[3]]
#> [1] 1.445749 5.826666 6.096497

Is there a simple way of achieving that?

I appreciate your time and attention.

Upvotes: 0

Views: 580

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 388817

You can do this with for loop and/or map but I think this is more of replicate or purrr::rerun problem.

In base R :

replicate(10, rnorm(n = 3, mean = 5, sd = 3), simplify = FALSE)

Or using purrr :

purrr::rerun(10, rnorm(n = 3, mean = 5, sd = 3))

Upvotes: 2

Ali
Ali

Reputation: 1080

There are two ways you can do this. The first is an anonymous function and the second is a formula. Refer to the examples in ?map() for more information.

  1. Anonymous Function

    library(purrr)
    1:10 %>%
      map(function(x) rnorm(n = 3, mean = 5, sd = 3))
    
  2. Formula

    1:10 %>%
      map(~ rnorm(n = 3, mean = 5, sd = 3))
    

Upvotes: 1

Related Questions