Creating multiple copies of the same data frame with unique values in a new column

Viewed 60

I have a very large dataset for which I would like to make multiple copies, but for each copy of this dataset, I want to give a distinct value in a new column. The purpose of this is to pair another set of data with this data set by those columns. Let me illustrate an example. Say my data set is the following:

id   value
X01    NA
X02    NA
X03    NA
X04    NA
X05    NA
X06    NA

I would like to make 32 copies of this data frame, and then for each copy, give it a distinct value in a third new column, called "character." That entire column could be populated with that value, by feeding it a list such as c("apple", "banana", "green", "red") etc. I want to do this so that once 32 distinct copies of this data set have been created, they can then be binded back together, with each of the 32 copies being sections of a new dataset, where the only difference between them is this new column of values. Does anyone know a good way of doing this? Previously, I have just created 32 data frames via the following process:

df_1 <- df %>% mutate(character = "apple")
df_2 <- df %>% mutate(character = "banana")


etc, and then binding them all together.

1 Answers

We can do this by looping the vector of values in a list and mutate new column

library(purrr)
library(dplyr)
library(stringr)
out <- map(c("apple", "banana"), ~ df %>% 
             mutate(character = .x))
names(out) <- str_c("df_", seq_along(out))
Related