Mirko Gagliardi
Mirko Gagliardi

Reputation: 69

How to create a set of data-frames based on a loop?

I need to create as many copies of the same df with as names of those data-frames changing values stored in a vector. For example:

z <- c("A-1", "B-2", "C-2", ...)

for (i in z) {
   i <- already_existing_df
  }

Manual hard-coding would be something like:

`A-1` <- df
`B-2` <- df
# ...and so on

Of course I would want to automate this, and not hardcode it... also 'cause it will change every month, and we are talking about many dfs...

Now, I know that to pass i as a variable name, you can simply do:

df[i]

but I don't know how to pass i as a df name.

Thank you in advance for any help!

Upvotes: 1

Views: 59

Answers (3)

Bob Jansen
Bob Jansen

Reputation: 1287

You can do assign(df, z) which will assign df to your enviroment under the i element of z.

Upvotes: 1

r.user.05apr
r.user.05apr

Reputation: 5456

Depending on your desired result you could define a list (or an Environment):

z <- vector("list", 3)

for (i in seq_along(z)) {
  z[[i]] <- already_existing_df
}

names(z) <- c("A-1", "B-2", "C-2")

Upvotes: 2

Ronak Shah
Ronak Shah

Reputation: 389235

Another approach could be using replicate to repeat the dataframe length(z) times and assign the names to the list

z <- c("A-1", "B-2", "C-2")
list_df <- setNames(replicate(length(z), df, simplify = FALSE), z)

You can then keep list of dataframes as it is or make them as separate dataframe.

list2env(list_df, .GlobalEnv)

Upvotes: 2

Related Questions