Search code examples
rlapplysapplymapply

Rename Columns of dataframe based on names of list in R


I have multiple dataframes saved in a list object. They share the same two column names. I'd like to rename the second column to the name of the dataframe.

Example Data:

df1 <- data.frame(A = 1:10, B= 11:20)
df2 <- data.frame(A = 21:30, B = 31:40) 
df3 <- data.frame(A = 31:40, B= 41:50)
df4 <- data.frame(A = 51:80, B = 61:70) 

listDF <- list(df1, df2,df3, df4)

I'm trying to use lapply to rename the second column to match the name of the dataframe.

# trying to rename second column after the element of the list they're located in
listDF_2 <- lapply(names(listDF), function(x) setNames(listDF[[x]], x) )

Solution

  • To keep track of names, you can use:

    listDF <- list(df1 = df1, df2 = df2, df3  = df3, df4 = df4)
    

    Then you can use for loop:

    for (i in names(listDF)){
      colnames(listDF[[i]]) <- c("A", i)
    }
    

    Or if you need to use lapply, you may use this:

    newDF <- lapply(names(listDF), function(x){
      colnames(listDF[[x]]) <- c("A", x)
      listDF[[x]]
    })
    names(newDF) <- names(listDF)