Mercelo
Mercelo

Reputation: 231

R change name of dataset with stored string

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)

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]
  }

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.

Upvotes: 0

Views: 6851

Answers (1)

Ciar&#225;n Tobin
Ciar&#225;n Tobin

Reputation: 7536

You can use list2env().

list2env(AllDatasets, .GlobalEnv)

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)

Or directly with a string:

assign('ThatOne', D)

Upvotes: 5

Related Questions