Search code examples
rlistrenamelapply

Rename single column in all dataframes in a list using a vector for the column names


I currently have a list of data frames and I want to rename the first column of each of them, using a vector.

I have tried the following:

cols <- c("list", "of", "names")
list <- lapply(list, function(x){
colnames(x)[1] <- cols; x})

But that has resulted in the first column of each dataframe in the list being renamed to the first element in my cols vector.

Anyone know how I can achieve this?


Solution

  • You need to map over both the list of names and the data.frames. You can map over multiple elements with Map rather than lapply

    cols <- c("list", "of", "names")
    list <- Map(function(x, name){
      colnames(x)[1] <- name; x}, list, cols)
    

    Tested with

    list <- replicate(3, data.frame(a=1:3, b=4:6), simplify = FALSE)