Search code examples
rdataframer-environment

How can I create a data frame with all existing variables (at once)?


It may sound trivial and the solution is probably quite simple but I can't figure it out.

I just want to combine all my variables in a data.frame. I wonder if there is a way to do that without choosing them one by one, but instead telling R that I want to use all of the already existing variables?

var1 <- c(1,2)
var2 <- c(3,4)

Instead of doing this

df <- data.frame(var1, var2)

I want to do something like this

df <- data.frame(-ALL_VARIABLES_IN_ENVIRONMENT-)

I've tried ls() (respectively objects()) also in combinatination with unquote() as well as names() but this only gives me a vector with names (undquoted or not) and not the environment's objects.


Solution

  • var1 <- 1:3
    var2 <- 1:3
    
    data.frame(sapply(ls(), get))
    
    #   var1 var2
    # 1    1    1
    # 2    2    2
    # 3    3    3