Sean Zhang
2009-Jul-27 03:16 UTC
[R] how to use do.call together with cbind and get inside a function
Dear R-helpers:
I have a question related to using do.call to call cbind and get.
#the following works
vec1 <- c(1,2)
vec2 <- c(3,4)
ColNameVec <- c('vec1','vec2')
mat <- do.call("cbind",lapply(ColNameVec,get))
mat
#put code above into a function then it does not work
#before doing so, first remove vec1 and vec2 from global environment
rm(vec1,vec2)
test <- function()
{
vec1 <- c(1,2)
vec2 <- c(3,4)
ColNameVec <- c('vec1','vec2')
mat <- do.call("cbind",lapply(ColNameVec,get))
return(mat)
}
test()
In my task, I have to run do.call("cbind",lapply(ColNameVec,get))
inside a function, can someone kindly help?
Many thanks in advance!
-Sean
[[alternative HTML version deleted]]
Gabor Grothendieck
2009-Jul-27 04:51 UTC
[R] how to use do.call together with cbind and get inside a function
Use lapply(ColNameVec, get, environment()) so that it gets the objects from the current environment. See: ?get ?environment On Sun, Jul 26, 2009 at 11:16 PM, Sean Zhang<seanecon at gmail.com> wrote:> Dear R-helpers: > I have a question related to using do.call to call cbind and get. > > #the following works > vec1 <- c(1,2) > vec2 <- c(3,4) > ColNameVec <- c('vec1','vec2') > mat <- do.call("cbind",lapply(ColNameVec,get)) > mat > > #put code above into a function then it does not work > #before doing so, first remove vec1 and vec2 from global environment > rm(vec1,vec2) > > test <- function() > { > vec1 <- c(1,2) > vec2 <- c(3,4) > ColNameVec <- c('vec1','vec2') > mat <- do.call("cbind",lapply(ColNameVec,get)) > return(mat) > } > test() > > In my task, I have to run do.call("cbind",lapply(ColNameVec,get)) > inside a function, can someone kindly help? > > Many thanks in advance! > > -Sean > > ? ? ? ?[[alternative HTML version deleted]] > > ______________________________________________ > R-help at r-project.org mailing list > 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. >