Vinay billa Vinay billa - 3 months ago 8
R Question

How to assign different column names within a list

I have a list with 15 data frames each have the following columns

> head(final_data[[1]])
DateTime Value
147 2013-03-01 2320.58
148 2013-04-01 2336.89
149 2013-05-01 2213.78
150 2013-06-01 2135.90
151 2013-07-01 2302.79
152 2013-08-01 2177.01


I want to change the name
"Value"
to a different name for all the dataframes such that the final names of the columns for these 15 dataframes must look like

names(final_data[[1]])
DateTime A

names(final_data[[2]])
DateTime B


Thank You.

Answer

We can use lapply to loop through the sequence of list and do the assignment

final_data2 <- lapply(seq_along(final_data), function(i) {
                                      d1 <- final_data[[i]]
                                       names(d1)[2] <- LETTERS[i]
                                       d1
            })

Or use Map

final_data2 <- Map(function(x,y) {names(x)[2] <- y; x}, final_data, LETTERS[1:15])