Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading