Home > database >  R: Set column name from dataframe name in list of dataframes
R: Set column name from dataframe name in list of dataframes

Time:03-29

I have a large list of dataframes like the following:

> head(lst)
$Set1
  ID Value
1  A     1
2  B     1
3  C     1

$Set2
  ID Value
1  A     1
2  D     1
3  E     1

$Set3
  ID Value
1  B     1
2  C     1

I would like to change the name of the column "Value" in each dataframe to be similar to the name of the dataframe, so that the list of dataframes looks like this:

> head(lst)
$Set1
  ID Set1
1  A     1
2  B     1
3  C     1

$Set2
  ID Set2
1  A     1
2  D     1
3  E     1

$Set3
  ID Set3
1  B     1
2  C     1

Can anyone think of a function that takes the name of each dataframe in the list and names the column accordingly? My original list has >400 dataframes, so I was hoping to automate this somehow. Sorry if this is a naive question, but I'm somehow stuck...

Thanks so much!

Here is an example of a list of dfs:

lst <- list(
  data.frame(ID = c("A", "B", "C"), Value = c(1, 1, 1)),
  data.frame(ID = c("A", "D", "E"), Value = c(1, 1, 1)),
  data.frame(ID = c("B", "C"), Value = c(1, 1)),
  data.frame(ID = c("B", "C"), Value = c(1, 1)),
  data.frame(ID = c("B", "C"), Value = c(1, 1)),
  data.frame(ID = c("B", "C"), Value = c(1, 1)))
lst_names <- c("Set1", "Set2", "Set3", "Set4", "Set5","Set6")
names(lst) <- lst_names

CodePudding user response:

In the tidyverse we can use purrr::imap and dplyr::rename:

library(purrr)
library(dplyr)

lst %>% 
  imap(~ rename(.x, "{.y}" := Value))
#> $Set1
#>   ID Set1
#> 1  A    1
#> 2  B    1
#> 3  C    1
#> 
#> $Set2
#>   ID Set2
#> 1  A    1
#> 2  D    1
#> 3  E    1
#> 
#> $Set3
#>   ID Set3
#> 1  B    1
#> 2  C    1
#> 
#> $Set4
#>   ID Set4
#> 1  B    1
#> 2  C    1
#> 
#> $Set5
#>   ID Set5
#> 1  B    1
#> 2  C    1
#> 
#> $Set6
#>   ID Set6
#> 1  B    1
#> 2  C    1

Created on 2022-03-28 by the reprex package (v2.0.1)

CodePudding user response:

We can do,

lapply(
  names(lst), 
  function(x) setNames(lst[[x]], c(names(lst[[x]])[2], x))
)

[[1]]
  Value Set1
1     A    1
2     B    1
3     C    1

[[2]]
  Value Set2
1     A    1
2     D    1
3     E    1
  • Related