1

I'm switching to collapse R package for better speed. However, I'm struggling to translate purrr::map and its variants into collapse code. Couldn't figured out how to translate 1:2 %>% map(.x = ., .f = rnorm, n = 3) into relevant collapse code. My attempt is below:

library(tidyverse)
suppressMessages(library(collapse))

1:2 %>%
  map(.x = ., .f = rnorm, n = 3)
#> [[1]]
#> [1]  1.0567499  0.6074554 -0.5142574
#> 
#> [[2]]
#> [1] 2.369641 2.895773 1.256230


1:2 %>%
  rapply2d(l =., FUN = rnorm, n = 3)
#> [1] 1.613705 1.338446 1.404881

1:2 %>%
  rapply2d(l =., FUN = rnorm, 3)
#> [1] 4.082665 3.827381

1:2 %>%
  rapply2d(l =., FUN = rnorm(n = 3))
#> Error in FUN(y, ...): could not find function "FUN"
Maël
  • 45,206
  • 3
  • 29
  • 67
MYaseen208
  • 22,666
  • 37
  • 165
  • 309
  • 3
    `rapply2d()` expects a list not a vector, so use `as.list(1:2)` and your first attempt should return a result equivalent to your `map()` code. That said, obviously `rapply2d()` is recursive where `map()` is not so that's something to watch out for (you may want to consider using `BY()` instead). Note, `collapse` shines when using its optimized inbuilt functions so if you don't use these you're unlikely to see much of a speed boost (e.g. switching from `map()` to `rapply2d()` won't speed things up much in itself). – Ritchie Sacramento Feb 28 '22 at 04:43
  • 1
    @RitchieSacramento: Please change your comment to answer. – MYaseen208 Feb 28 '22 at 05:58
  • 1
    I guess you can change it to lambda function i.e. `1:2 %>% rapply2d(l =., FUN = \(x) rnorm(x, n = 3))# [1] -0.9313985 2.6498940 1.1638518` (regarding the error part) For the list, as mentioned in the comments, the input should be a list `as.list(1:2)` – akrun Feb 28 '22 at 16:36
  • `rapply2d` is there to apply a function to a nested list of data frames. It is a wrapper around `lapply`. For most cases you'll prefer to use `lapply`, `sapply`, `rapply`etc. – Sebastian Mar 04 '22 at 20:42

0 Answers0