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

Altering the column names of dataframes in a list with lapply

I want to add a prefix to the colnames of dataframes in a list, based on the name of the dataframe:

list1 <- vector("list", 6)

list1 <- lapply(list1, function(x) data.frame(replicate(10,sample(0:1,10,rep=TRUE))))
list1 <- lapply(list1, function(x) {colnames(x)<- letters[1:10];x})
names(list1) <- LETTERS[1:6]

At this point, i want to change the colnames with something like:

    colnames(list1[[1]]) <- paste(names(list1[1]), colnames(list1[[1]]), sep=".")
    colnames(list1[[1]])
    [1] "A.a" "A.b" "A.c" "A.d" "A.e" "A.f" "A.g" "A.h" "A.i" "A.j"

How can i do this sequentally on each of the six dataframes? I tried

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

lapply(list1, function(x) {colnames(list1[x]) <- paste(names(list1[x]), colnames(list1[[x]]), sep=".");x })

but

Error in list1[x] : invalid subscript type 'list'

I guess its about cycling through the names of list1? Or how is it done?

Thanks for your help.

>Solution :

Using base R, you can use Map.

Map(function(x, y) setNames(x, paste(names(x), y, sep = ".")), list1, names(list1))

Here is another way using purrr. The i functions (e.g., imap, imodify) will pass the name of the list item in as parameter .y along with the list contents in .x.

library(purrr)

imodify(list1, ~ set_names(.x, paste(names(.x), .y, sep = ".")))
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