0

I have a list of dataframes and a list of labels (same length). I want to insert in a newly created column for each dataframe with the corresponding value in df_label. I've obviously managed to do so with a simple for loop but I'm sure there must be something from the apply family that might be more concise and elegant.

library(dplyr)

df_label <- c("df_1", "df_2", "df_3")
df_list <- list(iris[1:49,], iris[50:99,], iris[100:150,])

# Apply labels recursively
for (i in seq_along(df_list)) {
    df_list[[i]] <- df_list[[i]] %>% 
        mutate(label = df_label[i])
}

glimpse(df_list)

#> List of 3
#>  $ :'data.frame':    49 obs. of  6 variables:
#>   ..$ Sepal.Length: num [1:49] 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
#>   ..$ Sepal.Width : num [1:49] 3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
#>   ..$ Petal.Length: num [1:49] 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
#>   ..$ Petal.Width : num [1:49] 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
#>   ..$ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
#>   ..$ label       : chr [1:49] "df_1" "df_1" "df_1" "df_1" ...
#>  $ :'data.frame':    50 obs. of  6 variables:
#>   ..$ Sepal.Length: num [1:50] 5 7 6.4 6.9 5.5 6.5 5.7 6.3 4.9 6.6 ...
#>   ..$ Sepal.Width : num [1:50] 3.3 3.2 3.2 3.1 2.3 2.8 2.8 3.3 2.4 2.9 ...
#>   ..$ Petal.Length: num [1:50] 1.4 4.7 4.5 4.9 4 4.6 4.5 4.7 3.3 4.6 ...
#>   ..$ Petal.Width : num [1:50] 0.2 1.4 1.5 1.5 1.3 1.5 1.3 1.6 1 1.3 ...
#>   ..$ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 2 2 2 2 2 2 2 2 2 ...
#>   ..$ label       : chr [1:50] "df_2" "df_2" "df_2" "df_2" ...
#>  $ :'data.frame':    51 obs. of  6 variables:
#>   ..$ Sepal.Length: num [1:51] 5.7 6.3 5.8 7.1 6.3 6.5 7.6 4.9 7.3 6.7 ...
#>   ..$ Sepal.Width : num [1:51] 2.8 3.3 2.7 3 2.9 3 3 2.5 2.9 2.5 ...
#>   ..$ Petal.Length: num [1:51] 4.1 6 5.1 5.9 5.6 5.8 6.6 4.5 6.3 5.8 ...
#>   ..$ Petal.Width : num [1:51] 1.3 2.5 1.9 2.1 1.8 2.2 2.1 1.7 1.8 1.8 ...
#>   ..$ Species     : Factor w/ 3 levels "setosa","versicolor",..: 2 3 3 3 3 3 3 3 3 3 ...
#>   ..$ label       : chr [1:51] "df_3" "df_3" "df_3" "df_3" ...

Created on 2020-06-08 by the reprex package (v0.3.0)

anddt
  • 1,589
  • 1
  • 9
  • 26

1 Answers1

2

You can use Map :

df_list <- Map(cbind, df_list, label = df_label)

Equivalent in purrr :

df_list <- map2(df_list, df_label, ~cbind(.x, label = .y))

If you want to use lapply you can iterate over the list using seq_along.

df_list <- lapply(seq_along(df_list), function(x) 
                 cbind(df_list[[x]], label = df_label[x]))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213