Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use purrr tilde function with multi-line formulas

Tags:

r

purrr

I would like to use purrr's short-hand formula specification with multi-line formulas.

For example, I would like to repurpose the following formula:

purrr::imap_chr(sample(10), ~ paste0(.y, ": ", .x))

And do the following instead:

purrr::imap_chr(sample(10), ~ 
     b <- 10
     paste0(.y, ": ", .x + b))

However, I receive an error when I attempt to do this:

Error: unexpected symbol in: " b <- 10 paste0"

like image 982
matsuo_basho Avatar asked Oct 22 '25 04:10

matsuo_basho


1 Answers

We can use braces { to create multi-line formulas

purrr::imap_chr(sample(10), ~ {
 b <- 10
 paste0(.y, ": ", .x + b)
 })
#[1] "1: 18"  "2: 16"  "3: 19"  "4: 11"  "5: 13"  "6: 12"  "7: 15"  "8: 14"  "9: 17"  "10: 20"
like image 173
akrun Avatar answered Oct 23 '25 18:10

akrun