[R] passing elements of named vector / named list to function
Rainer M Krug
Rainer at krugs.de
Thu Jan 15 15:25:43 CET 2015
Hi
Following scenario: I have a function fun
--8<---------------cut here---------------start------------->8---
fun <- function(A, B, C, ...){paste(A, B, C, ...)}
--8<---------------cut here---------------end--------------->8---
and x defined as follow
--8<---------------cut here---------------start------------->8---
x <- 1:5
names(x) <- LETTERS[x]
--8<---------------cut here---------------end--------------->8---
now I want to pass the *elements* of x to fun as named arguments, i.e.
,----
| > fun(A=1, B=2, C=3, D=4, E=5)
| [1] "1 2 3 4 5"
`----
The below examples obviously do not work:
,----
| > fun(x)
| Error in paste(A, B, C, list(...)) :
| argument "B" is missing, with no default
| > fun(unlist(x))
| Error in paste(A, B, C, list(...)) :
| argument "B" is missing, with no default
`----
How can I extract from x the elements and pass them on to fun()?
I could easily change x to a list() if this would be easier.
--8<---------------cut here---------------start------------->8---
x <- list(A=1, B=2, C=3, D=4, E=5)
--8<---------------cut here---------------end--------------->8---
In my actual program, x can have different elements as well as fun -
this is decided programmatically.
Any suggestions how I can achieve this?
Thanks,
Rainer
--
Rainer M. Krug
email: Rainer<at>krugs<dot>de
PGP: 0x0F52F982
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 494 bytes
Desc: not available
URL: <https://stat.ethz.ch/pipermail/r-help/attachments/20150115/6804491d/attachment.bin>
More information about the R-help
mailing list