Reputation: 69
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
Reputation: 1287
You can do assign(df, z)
which will assign df
to your enviroment under the i
element of z
.
Upvotes: 1
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
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