I have two data frames, df1_09 and df1_10, that I put together in a list, list_of_df:
library(tidyverse)
df1_09 <- data.frame(
index = c(1, 1, 2, 2),
first_column = c(1, 2, 3, 4),
second_column = c(5, 6, 7, 8)
)
df1_10 <- data.frame(
index = c(1, 1, 2, 2),
first_column = c(4, 2, 3, 1),
second_column = c(8, 6, 7, 5)
)
list_of_df <- list(df1_09, df1_10)
Now I create a function that takes in one of the original data frames, df1_09, groups the values according to the index variable, and calculates the means for each column. The function also creates an additional column called type with the name of the data frame.
output_mean <- function(subset, name) {
subset %>%
group_by(index) %>%
summarize(across(c(first_column, second_column), ~ mean(.x, na.rm = TRUE))) %>%
mutate(type = name) %>%
print()
}
output_mean(df1_09, "df1_09")
#> # A tibble: 2 x 4
#> index first_column second_column type
#> <dbl> <dbl> <dbl> <chr>
#> 1 1 1.5 5.5 df1_09
#> 2 2 3.5 7.5 df1_09
Now what I would like to do, is to loop through the list list_of_df and get the same result. I have tried the following:
for (i in list_of_df) {
output_mean(i, "i")
}
#> # A tibble: 2 x 4
#> index first_column second_column type
#> <dbl> <dbl> <dbl> <chr>
#> 1 1 1.5 5.5 i
#> 2 2 3.5 7.5 i
#> # A tibble: 2 x 4
#> index first_column second_column type
#> <dbl> <dbl> <dbl> <chr>
#> 1 1 3 7 i
#> 2 2 2 6 i
The problem is that I don't know how to get to the names of each object in the list. Have the names being deleted with the creation of the list?
Created on 2021-05-02 by the reprex package (v2.0.0)