12

Of course I could name the objects in my list all manually like this:

    #create dfs
    df1<-data.frame(a=sample(1:50,10),b=sample(1:50,10),c=sample(1:50,10))
    df2<-data.frame(a=sample(1:50,9),b=sample(1:50,9),c=sample(1:50,9))
    df3<-data.frame(a=sample(1:50,8),b=sample(1:50,8),c=sample(1:50,8))

    #make them a list
    list.1<-list(df1=df1,df2=df2,df3=df3)

But it makes a lot of work if I have let's say 50 objects with long names. So is there any way to automate this and make the names inside the list the same as the outside objects?

Joschi
  • 2,941
  • 9
  • 28
  • 36
  • 2
    See also [Can lists be created that name themselves based on input object names?](https://stackoverflow.com/questions/16951080/can-lists-be-created-that-name-themselves-based-on-input-object-names) – Henrik May 02 '18 at 14:22
  • 2
    Possible duplicate of [Can lists be created that name themselves based on input object names?](https://stackoverflow.com/questions/16951080/can-lists-be-created-that-name-themselves-based-on-input-object-names) – see24 Oct 29 '18 at 15:41

3 Answers3

9

Find the names, then call mget.
If there is a pattern to the names of each individual variable, then this is straightforward.

var_names <- paste0("df", 1:3)
mget(var_names, envir = globalenv())  #or maybe envir = parent.frame()

If the naming system is more complicated, you can use regular expressions to find them, using something like

var_names <- ls(envir = globalenv(), pattern = "^df[[:digit:]]+$")
Richie Cotton
  • 118,240
  • 47
  • 247
  • 360
3

If you just want to name a list with names from the environment that share something, in this case 'df':

names(list.1) <- grep("df",ls(),value=TRUE)

If you want to push your environment into a list:

list.1 <- globalenv()
list.1 <- as.list(list.1) 

To reverse the process see ?list2env

Brandon Bertelsen
  • 43,807
  • 34
  • 160
  • 255
0

As noted in the possible duplicate questions' responses:

From the tidyverse, use tibble:lst: https://tibble.tidyverse.org/reference/lst.html

Scott Kaiser
  • 307
  • 4
  • 11