I have a list
of 11 data frames, the name of each data frame describes its source. Essentially I want to add a "source" column to each data frame in the list which contains the name of the data frame in each cell.
This is all so the data can be passed downstream to a CRAN package which doesn't play well with lists.
I've tried using lapply
and looked through some other SO answers but nothing seems to fit.
Any help is greatly appreciated,
- Thanks
## Some toy data
p1 <- c("A", "B", "C", "D", "E")
p2 <- c(rnorm(5, 1.25, 1))
p3 <- c(rnorm(5, 1.25, 1))
source_name_1 <- data.frame(p1, p2, p3)
p2 <- c(rnorm(5, 1.25, 1))
p3 <- c(rnorm(5, 1.25, 1))
source_name_2 <- data.frame(p1, p2, p3)
p2 <- c(rnorm(5, 1.25, 1))
p3 <- c(rnorm(5, 1.25, 1))
source_name_3 <- data.frame(p1, p2, p3)
df_list <- list(source_name_1,
source_name_2,
source_name_3)
names(df_list) = paste0("source_name_", 1:length(df_list))
## Previous attempt based on other SO answers
df_list_2 <- lapply(names(df_list),
function(x) cbind(df_list),
source = names(df_list),
SIMPLIFY = TRUE)
#essentially I'm aiming for a 'p4' column in each df comprised of `^source_name[1-9]`