[R] do.call help

Sundar Dorai-Raj sundar.dorai-raj at pdf.com
Thu Mar 2 22:09:56 CET 2006



Andy Bunn wrote:
> Hello all:
> 
> I have a character variable (foo) that contains the names of some numeric
> variables. For my application, I'd like to cbind the numeric variables and
> calculate the row mean using the character variable. I think I do this using
> do.call but the function to call using do.call is eluding me! Example below
> and help appreciated.
> TIA,
> -Andy
> 
> 
> x1<-x2<-x3<-x4<-rnorm(10)
> foo <- c("x1","x2","x3","x4")
> 
> # what I want...
> rowMeans(cbind(x1,x2,x3,x4))
> 
> bar <- function(aCharVaraible) {
>     cbind(stuff goes here)
>     rowMeans(stuff goes here)
> }
> # how I want to get it...
> do.call("bar",foo)
> 

How about:

set.seed(42)
x1 <- x2 <- x3 <- x4 <- rnorm(10)
foo <- c("x1","x2","x3","x4")
bar <- function(x) {
   y <- do.call("cbind", lapply(x, get))
   rowMeans(y)
}

do.call("bar", list(foo))

HTH,

--sundar




More information about the R-help mailing list