【发布时间】:2021-05-02 19:22:06
【问题描述】:
我有两个数据框,df1_09 和 df1_10,我将它们放在一个列表中,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)
现在我创建了一个函数,它接收一个原始数据帧df1_09,根据index 变量对值进行分组,并计算每列的平均值。该函数还会创建一个名为 type 的附加列,其中包含数据框的名称。
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
现在我想做的是循环 遍历列表list_of_df 并获得相同的结果。我尝试了以下方法:
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
问题是我不知道如何获取列表中每个对象的名称。名称是否随着列表的创建而被删除?
由reprex package (v2.0.0) 于 2021 年 5 月 2 日创建
【问题讨论】: