On Apr 23, 2015, at 5:41 PM, Erin Hodgess <erinm.hodg...@gmail.com> 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
> 
> 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.
> 
> Thanks,
> Erin
> 


Hi Erin,

One approach could be:

> sapply(big.char, get, mode = "integer")
     dog cat tree
[1,]   1   2    5
[2,]   2   3    6
[3,]   3   4    7

or

> sapply(big.char, get, mode = "numeric")
     dog cat tree
[1,]   1   2    5
[2,]   2   3    6
[3,]   3   4    7


Note that I used the ‘mode' argument to get(). You used ‘cat’ as the name of 
one of the objects and of course, there is an R function cat(). By default for 
get(), mode = “any”, which would otherwise result in:

> sapply(big.char, get)
$dog
[1] 1 2 3

$cat
function (..., file = "", sep = " ", fill = FALSE, labels = NULL, 
    append = FALSE) 
{
    if (is.character(file)) 
        if (file == "") 
            file <- stdout()
        else if (substring(file, 1L, 1L) == "|") {
            file <- pipe(substring(file, 2L), "w")
            on.exit(close(file))
        }
        else {
            file <- file(file, ifelse(append, "a", "w"))
            on.exit(close(file))
        }
    .Internal(cat(list(...), file, sep, fill, labels, append))
}
<bytecode: 0x7fe942d78f78>
<environment: namespace:base>

$tree
[1] 5 6 7


In the above, the cat() function body is returned, instead of the vector cat. 
So just need to be cautious.

An alternative approach, depending upon where your vectors are stored, might be:

> sapply(big.char, get, pos = 1)
     dog cat tree
[1,]   1   2    5
[2,]   2   3    6
[3,]   3   4    7


which specifies which environment to search for the named objects and the cat() 
function is not returned since it is in namespace:base.

See ?get

Regards,

Marc Schwartz

______________________________________________
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to