如何更改列表中的 df 列名称

How to change the df column name within a list

我有一个 dfs 列表。 dfs 都具有相同的列名。我想:

(1) 将其中一个列名更改为列表中df的名称

(2) full_join 更名后的所有dfs

我的列表示例:

my_list <- list(one = data.frame(Type  = c(1,2,3), Class = c("a", "a", "b")),
                two = data.frame(Type  = c(1,2,3), Class = c("a", "a", "b")))

我想要的输出:

data.frame(Type = c(1,2,3),
           one  = c("a", "a", "b"),
           two  = c("a", "a", "b"))

  Type one two
    1   a   a
    2   a   a
    3   b   b

您可以结合使用 dplyr::bind_rowstidyr::spread 来获得相同的结果(如果您愿意考虑其他方法)。例如:

library(tidyverse)
my_list %>% bind_rows(.id = "groups") %>% spread(groups, Class)

#>   Type one two
#> 1    1   a   a
#> 2    2   a   a
#> 3    3   b   b

第一步可能会很棘手,但如果您遍历 names(my_list) 就很简单了。

transformed <- sapply(names(my_list), function(name) {
  df <- my_list[[name]]
  colnames(df)[colnames(df) == 'Class'] <- name
  df
}, simplify = FALSE, USE.NAMES = TRUE)

purrr::reducedplyr::full_join可以得到结果:

purrr::reduce(transformed, dplyr::full_join)
#   Type one two
# 1    1   a   a
# 2    2   a   a
# 3    3   b   b