[R] Using character vectors to call data in the "cbind" command

Prof Brian Ripley ripley at stats.ox.ac.uk
Sun Mar 7 09:23:53 CET 2004


On Sat, 6 Mar 2004, alex pegucci wrote:

>  I have searched the forum but could not find a thread about the way to
> solve my problem. I am trying to find a way to use a subset of a list of
> variable names I have when I call the "cbind" command to create a data
> matrix, after I have attached a dataset. The nature of my program
> necessitates that I create different data matrices using a subset of
> variable names multiple times. So, when I change the variables for the
> analysis, I need to make 5-6 manipulations to my program and it is
> painful. Is there a way to use a character vector containing variable
> names in the cbind command? What I tried is

> 1.I loaded and attached a data set.
> 2.I have a character vector containing the variables I want to use in
> the analysis. Say
>  name <- c("a1","a2","a3", "a4")

> I have several vectors of this type to use in the analysis, so to
> create a data matrix, I use the cbind command but as expected the
> following does not work:
>
> X <- cbind(1, name)
> cbind requires "," between the variable names so when I do
> X <- cbind(1, paste(",", name, collapse=""))
> it still doesn't work although the printed version of the second portion
> is more or less what I need.
>  
> Is there a way to do this?

Several.  Perhaps the easiest is

eval(parse(text=paste("cbind(1,", paste(name, collapse=","), ")")))

which constructs the command you would type in and submits it.

Another way would be to use do.call(), as in

do.call("cbind", c(1, lapply(name, get)))

although if you want dimnames

tmp <- lapply(name, get); names(tmp) <- name
do.call("cbind", c(1, tmp))

is needed.


-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595




More information about the R-help mailing list