Search code examples
rloopsfor-loopnames

Renaming the headers of every data frame in a list


I have a list containing a number of data frames, all with the same number of columns.

E.g, for a list df_list with two data frames, df1 and df2:

>df_list

df1
a    b    c
1    1    1
2    2    2
3    3    3

df2
a    b    c
3    2    1
3    2    1
3    2    1

I want to rename the headers of every data frame to new_headings <- c("A", "B", "C").

I constructed a for loop:

for (i in 1:length(list)) {
     names(list[[i]]) <- new_headings
}

However, this doesn't work. The headings remain as they were. If I do it individually instead of in a loop, it works fine, however, e.g., names(list[[1]]) <- new_headings changes the headings appropriately.

My actual list is very long with many data frames. Can anyone explain why this isn't working or what other approach I can use? Thank you.


Solution

  • We can use Map with setNames

    df_listNew <- Map(setNames, df_list, list(new_headings))
    

    Or using lapply

    lapply(df_list, setNames, new_headings)
    #$df1
    #  A B C
    #1 1 1 1
    #2 2 2 2
    #3 3 3 3
    
    #$df2
    #  A B C
    #1 3 2 1
    #2 3 2 1
    #3 3 2 1
    

    data

    df_list <- list(df1 = structure(list(a = 1:3, b = 1:3, c = 1:3), 
           class = "data.frame", row.names = c(NA, 
    -3L)), df2 = structure(list(a = c(3, 3, 3), b = c(2, 2, 2), c = c(1, 
    1, 1)), class = "data.frame", row.names = c(NA, -3L)))