I'm creating lots of datasets with a loop and I need to make sure that all these different datasets are properly named and stored in the workspace. My question is the following. Let's say I have a dataset (here airquality), I want to create 4 datasets and store them in the workspace
Split dataset
airquality$N<-letters[airquality$Month]
head(airquality)
AllDatasets<-split(airquality,airquality$N)
names(AllDatasets)
Run Code Online (Sandbox Code Playgroud)
Now I want to extract each dataset with a loop, for example
#Conceptual loop
for (i in (1:names(AllDatasets))){
#Create dataset AllDatasets[i] and name it names(AllDatasets)[i]
}
Run Code Online (Sandbox Code Playgroud)
so that after the loop I can work with each dataset (e, f, g, h, i) separately ( I don't want to apply the same function to all datasets, I want to store each single one independently in my workspace). I suppose the question doesn't just apply to loops, it's about how to rename a dataset (not its columns) with a name stored in a string.
You can use list2env().
list2env(AllDatasets, .GlobalEnv)
Run Code Online (Sandbox Code Playgroud)
Now e, f, g, h and i are available in your workspace (global environment in this case, you can specify a different environment in the second argument if you like).
To assign a name from a string you can use assign(). E.g. in response to Marco's comment below:
D <- data.frame(rnorm(1:10), rnorm(1:2))
Name <- 'ThatOne'
assign(Name, D)
Run Code Online (Sandbox Code Playgroud)
Or directly with a string:
assign('ThatOne', D)
Run Code Online (Sandbox Code Playgroud)