Search code examples
rcbind

Including the variables in a global environment in a dataset


I have about 70 variables in the global environment in RStudio and would like to turn them into a data frame – one column for each variable. Each variable has a length of 1,500. Is there a way to quickly do this?


Solution

  • This seems to work:

    data.frame(mget(ls()))

    I can break this down a bit...

    ls() returns a character vector containing the names of all variables in the global environment.

    mget() returns the values bound to names contained in a character vector. The values are returned as a named list.

    data.frame() just converts the named list of vectors to a data.frame.

    If you want to build the data.frame using only a subset of the names in the global environment, try the pattern argument in ls(). For instance, to build a data.frame using only names that start with the letter "m":

    data.frame(mget(ls(pattern = "^m.*")))