Rename 1-st variables' name in multiple dataframes

Hi,
is it posiible to batch rename first variable in many dataframes acording to a vector ?
Let's say I have got a few dataframes d1 to d13. In each and every of these dataframes the first variable's name is Var1. I want to change this according to a vector:

c("PassengerId", "Survived", "Pclass","Name","Sex","Age","SibSp", "Parch","Ticket","Fare","Cabin","Embarked" ,"Survived_1")

dfs <- list(df1, df2, df3, df4, df5, df6, df7, df8, df9, df10, df11, df12, df13)

So in df1 instead of Var1 it will change to "PassengerId".

My second question is: how to create such a list:

dfs <- list(df1, df2, df3,df4, df5,df6,df7,df8,df9,df10,df11,df12,df13)

I have done it by writing it down one by one as:

dfs <- list(df1:df13)

doesn't work.

Thank you for your kind help.

Here is method one

library(purrr)
df1 <- data.frame(V1=1:3,V2=1:3)
df2 <- data.frame(V1=2:4,V2=2:4)
df3 <- data.frame(V1=3:5,V2=3:5)
Nms <- paste0("df",1:3)
ListOfDF <- map(Nms,get)
ListOfDF
#> [[1]]
#>   V1 V2
#> 1  1  1
#> 2  2  2
#> 3  3  3
#> 
#> [[2]]
#>   V1 V2
#> 1  2  2
#> 2  3  3
#> 3  4  4
#> 
#> [[3]]
#>   V1 V2
#> 1  3  3
#> 2  4  4
#> 3  5  5

ColNames <- c("PassengerId", "Survived", "Pclass")
ReName <- function(N,D) {
  colnames(D)[1] <- N
  return(D)
}

ListOfDF <- map2(ColNames, ListOfDF, ReName)
ListOfDF
#> [[1]]
#>   PassengerId V2
#> 1           1  1
#> 2           2  2
#> 3           3  3
#> 
#> [[2]]
#>   Survived V2
#> 1        2  2
#> 2        3  3
#> 3        4  4
#> 
#> [[3]]
#>   Pclass V2
#> 1      3  3
#> 2      4  4
#> 3      5  5

Created on 2022-01-09 by the reprex package (v2.0.1)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.