Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

mapply for a single list

I understand the usage of mapply(FUN, ...) that cycles through elements of each of the ... arguments and applies FUN to those combinations. What if instead of multiple arguments in ... I have them in one list?

Example use case:
I define a function that pastes arguments excluding NA:

pasteNotNA <- function(...,collapse=', '){
  dots <- list(...);
  paste(na.omit(unlist(dots)),collapse=collapse)
}

pasteNotNA('a',NA,'c')
# "a, c"

I can apply it element-wise for vectors if I pass them explicitly to mapply:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

mapply(pasteNotNA, c('a',NA,'c'),c('X','Y','Z'),c('1','2',NA),USE.NAMES = F)
# "a, X, 1"   "Y, 2"    "c, Z" 

What I want is to apply it to a list and get the same result:

inp_list <- list(vec1=c('a',NA,'c'), vec2=c('X','Y','Z'), vec3=c('1','2',NA))
some_apply(pasteNotNA, inp_list)
# "a, X, 1"   "Y, 2"    "c, Z"

I guess it must be also something from *apply() or Map() family but can’t find the good solution…

>Solution :

Use do.call :

do.call("mapply", c(pasteNotNA, inp_list, USE.NAMES = FALSE))
## [1] "a, X, 1" "Y, 2"    "c, Z"  

or use pmap_chr in the purrr package:

library(purrr)

pmap_chr(inp_list, pasteNotNA)
## [1] "a, X, 1" "Y, 2"    "c, Z"   
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading