nateroe
nateroe

Reputation: 547

Using lapply to change column names of list of dataframes with different column names

I have three dataframes with different column names:

df1 <- data.frame(A = 1:10, B = 10:19)
df2 <- data.frame(D = 20:29, E = 30:39)
df3 <- data.frame(G = 40:49, H = 50:59)

They are in a list:

my_list <- list(df1, df2, df3)

I need to change the column names (ie A becomes A1, B becomes B2, D becomes D2, etc....). No, it is not as easy as appending a 2 on all column names. My real situation will involved unique changes (ie. A becomes 'species', B becomes 'abundance', etc.)

There are good answers for how to do this when the dataframes within the list all have the same column names (Using lapply to change column names of a list of data frames).

My dataframes have different names though. It would be nice to use something similar to the functionality of mapvalues.

Upvotes: 0

Views: 283

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388807

You can create a dataframe with the information of from and to and with lapply use setNames to match and replace the column names :

lookup_names <- data.frame(from = c("A", "B", "D", "E", "G", "H"), 
                           to = c("this", "that", "he", "she", "him", "her"))

lookup_names
#  from   to
#1    A this
#2    B that
#3    D   he
#4    E  she
#5    G  him
#6    H  her

lapply(my_list, function(x) 
        setNames(x, lookup_names$to[match(names(x), lookup_names$from)]))

#[[1]]
#   this that
#1     1   10
#2     2   11
#3     3   12
#4     4   13
#...
#...

#[[2]]
#   he she
#1  20  30
#2  21  31
#3  22  32
#4  23  33
#5  24  34
#....

Upvotes: 1

Related Questions