0

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.

nateroe
  • 487
  • 3
  • 20
  • 1
    So do you have vector of size 6 stored somewhere to be appended to already existing column names? How are the old and new names to be appended mapped? Is it based on position or name of the columns? – Ronak Shah Oct 19 '20 at 03:37
  • @RonakShah I want to be able to map changes based on name, similar to how ```mapvalues``` works: ```mapvalues(df$column, from = c("A", "B", "D", "E", "G", "H"), to = c("A2", "B2", "D2", "E2", "G2", "H2"))```. But of course, I need to be changing column names using ```lapply``` unlike the example here where values are just being changed within a column. – nateroe Oct 19 '20 at 03:46
  • They must be mapped by name and capable of this too: ```mapvalues(df$column, from = c("A", "B", "D", "E", "G", "H"), to = c("this", "that", "he", "she", "him", "her"))``` – nateroe Oct 19 '20 at 03:50

1 Answers1

1

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
#....
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213