Prevent coersion to a single type in unlist() or c(); passing arguments to wrapper functions

Posted by Leo Alekseyev on Stack Overflow See other posts from Stack Overflow or by Leo Alekseyev
Published on 2011-01-07T10:46:24Z Indexed on 2011/01/08 8:53 UTC
Read the original article Hit count: 168

Filed under:

Is there a simple way to flatten a list while retaining the original types of list constituents?.. Is there a way to programmatically construct a heterogeneous list?..

For instance, I want to create a simple wrapper for functions like png(filename,width,height) that would take device name, file name, and a list of options. The naive approach would be something like

my.wrapper <- function(dev,name,opts) { do.call(dev,c(filename=name,opts)) }

or similar code with unlist(list(...)). This doesn't work because opts gets coerced to character, and the resulting call is e.g. png(filename,width="500",height="500").

If there's no straightforward way to create heterogeneous lists like that, is there a standard idiomatic way to splice arguments into functions without naming them explicitly (e.g. do.call(dev,list(filename=name,width=opts["width"]))?

-- Edit --

Gavin Simpson answered both questions below in his discussion about constructing wrapper functions. Let me give a summary of the answer to the title question:

It is possible to construct a heterogeneous list with c() provided the arguments to c() are lists. To wit:

> foo <- c("a","b"); bar <- 1:3
> c(foo,bar)
[1] "a" "b" "1" "2" "3"
> c(list(foo),list(bar))
[[1]]     [1] "a" "b"
[[2]]     [1] 1 2 3
> c(as.list(foo),as.list(bar)) ## this creates a flattened heterogeneous list
[[1]]     [1] "a"
[[2]]     [1] "b"
[[3]]     [1] 1
[[4]]     [1] 2
[[5]]     [1] 3

© Stack Overflow or respective owner

Related posts about r