yakumo
yakumo

Reputation: 27

R: Set column name from dataframe name in list of dataframes

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

Upvotes: 2

Views: 1006

Answers (3)

juarpasi
juarpasi

Reputation: 88

You can also make a function to change one column from a datafram

changeOneColumName <- function(df, oldName, newName){
  names(df)[names(df) == oldName] <- newName
  return(df)
}

And then, apply that function with the Map

Map(changeOneColumName, lst, oldName = 'Value', newName = names(lst)) 

Upvotes: 0

TimTeaFan
TimTeaFan

Reputation: 18581

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)

Upvotes: 5

Nad Pat
Nad Pat

Reputation: 3173

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

Upvotes: 2

Related Questions