Reputation: 43
How to save multiple variables in global environment into a dataframe in R? I can do it one by one using the $. But is there a command that moves all variables at once?
Upvotes: 1
Views: 1414
Reputation: 263331
If there is a named list of objects, then:
cbind(dfrm, list.obj)
E.g.
dados <- data.frame(x=1:10, v1=rnorm(10), v2=rnorm(10))
dat1 <- rnorm(10)
dat2 <- letters[1:5]
cbind(dados, list(new1=dat1, new2=dat2))
Can also use this form:
cbind(dados, new1=dat1, new2=dat2)
If you had a bunch of variables in the global environment with the character string "zzz" in their names and you wanted to append them columnwise to an existing dataframe, you could use this:
dados[, ls(patt="zzz") ] <- sapply( ls(patt="zzz"), get)
You might notice that I was objecting to using data.frame(cbind(...))
and yet I am saying to use cbind
. Well, I am assuming that the first argument in my case is already a dataframe, so that cbind
does not get called, but rather cbind.data.frame' gets called, and it will allow the usual list-behavior of data.frame objects to persist. If the first argument is only a vector, then
.Internal(cbind(...)` will do coercion to a matrix which will remove attributes of all the arguments and coerce then into a common storage mode.
Upvotes: 0
Reputation: 17412
You can do:
do.call(data.frame, lapply(ls(), get))
But let me just say this sounds like a horrible idea.
Upvotes: 4