Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Altering the column names of dataframes in a list with lapply

Tags:

r

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

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.

like image 547
nouse Avatar asked Dec 18 '25 02:12

nouse


1 Answers

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 = ".")))

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!