Home > Software engineering >  mapply for a single list
mapply for a single list

Time:04-01

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:

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...

CodePudding user response:

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"   
  • Related