根据数据框中的值重命名大量数据框中的列

Renaming columns in a large list of dataframes based on value in dataframe

我有一个包含 24 个元素的大列表,所有数据框都具有相同的列。我将在这里给出一个简化的数据示例:

df1 <- data.frame(location = c(123, 123, 123, 123, 123),
              value = c('a', 'b', 'c', 'd', 'e'),
              rainfall = c(1, 1, 0, 0, 1))


df2 <- data.frame(location = c(246, 246, 246, 246, 246),
              value = c('a', 'b', 'c', 'd', 'e'),
              rainfall = c(1, 1, 0, 0, 1))

df3 <- data.frame(location = c(369, 369, 369, 369, 369),
              value = c('a', 'b', 'c', 'd', 'e'),
              rainfall = c(1, 1, 0, 0, 1))

alldfs <- list(df1, df2, df3)

我想创建一个新的数据框,其中包含不同位置(1、2 和 3)的降雨量值,如下所示:

Rainfall.123 Rainfall.246 Rainfall.369
1 1 1
1 1 1

我的数据集比这大得多,并且有不同的列名等,所以我需要对此进行编程,以便它从 'location' 列读取值并重命名 'rainfall' 列基于这个值。我想用降雨量值创建箱线图,并需要它们有不同的名称才能做到这一点。

我试过:

alldfs <- lapply(
  alldfs, function(df) {
    df$rainfall %>% rename_with( ~ "Rainfall",paste(df$location))
  }
)

但这行不通 - 我觉得一定有一个我缺少的简单解决方案...

谢谢!

您可以使用 bind_rows() 将数据集堆叠在一起,然后重塑数据:

bind_rows(alldfs) %>%
    pivot_wider(id_cols = "value", names_from = location, 
                values_from = rainfall, names_prefix = "rainfall.")
# A tibble: 5 x 4
  value rainfall.123 rainfall.246 rainfall.369
  <fct>        <dbl>        <dbl>        <dbl>
1 a                1            1            1
2 b                1            1            1
3 c                0            0            0
4 d                0            0            0
5 e                1            1            1