3

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)

1 Answer 1

1

We can create a named list, loop over the names of the list, extract the list element with [[ while passing the name argument as i

list_of_df <- dplyr::lst(df1_09, df1_10)
for (i in names(list_of_df)) {
   output_mean(list_of_df[[i]], i)
  }

-output

# 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
# A tibble: 2 x 4
#  index first_column second_column type  
#* <dbl>        <dbl>         <dbl> <chr> 
#1     1            3             7 df1_10
#2     2            2             6 df1_10
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.