[R] cbind question, please

Rolf Turner r.turner at auckland.ac.nz
Fri Apr 24 03:10:01 CEST 2015


On 24/04/15 10:41, Erin Hodgess wrote:
> Hello!
>
> I have a cbind type question, please:  Suppose I have the following:
>
> dog <- 1:3
> cat <- 2:4
> tree <- 5:7
>
> and a character vector
> big.char <- c("dog","cat","tree")
>
> I want to end up with a matrix that is a "cbind" of dog, cat, and tree.
> This is a toy example.  There will be a bunch of variables.
>
> I experimented with "do.call", but all I got was
> 1
> 2
> 3

I don't understand how you managed to get *that*.  When I did the 
"obvious" thing --- do.call(cbind,as.list(big.char)) --- I got
(as expected :-) )

      [,1]  [,2]  [,3]
[1,] "dog" "cat" "tree"

>
> Any suggestions would be much appreciated.  I still think that do.call
> might be the key, but I'm not sure.
>
> R Version 3-1.3, Windows 7.

do.call(cbind,lapply(big.char,get,envir=.GlobalEnv))

Note:  I had to throw in the specification of "envir" otherwise get() 
got the cat() function from "base" rather than your vector "cat".

Probably not a problem for your real application; shouldn't hurt, but.

Another salutary example of why it's not a good idea to give data sets 
names that are names of R built-ins.

cheers,

Rolf

-- 
Rolf Turner
Technical Editor ANZJS
Department of Statistics
University of Auckland
Phone: +64-9-373-7599 ext. 88276
Home phone: +64-9-480-4619



More information about the R-help mailing list