Use object names in list names in R

Of course, I could name the objects in my list all manually as follows:

#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 that does a lot of work, if I allow you to say 50 objects with long names. So, is there a way to automate this and make the names inside the list the same as external objects?

+4
source share
2 answers

Find the names, then call mget .
If there is a template for the names of each individual variable, 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 complex, you can use regular expressions to find them using something like

 var_names <- ls(envir = globalenv(), pattern = "^df[[:digit:]]+$") 
+8
source

If you just want to name a list with names from an environment in which there is something, in this case 'df':

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

If you want to push your environment to the list:

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

To cancel the process, see ?list2env

+3
source

Source: https://habr.com/ru/post/1468990/


All Articles