Home > Back-end >  change rownames in a list of data.frames using a master data.frame
change rownames in a list of data.frames using a master data.frame

Time:08-03

I have a bunch of lists, and I want to rename the rows using a master data.frame.

Here's an example list I created:

df <- data.frame(Value = c(1, 0, 6, 3, 4))
rownames(df) <- c("B144","B211","B678","B111", "B7090")
df2 <- data.frame(Value = c(0, 0, 1, 4, 2))
rownames(df2) <- c("V2","V543","V6577","V4322", "V55")

List<-list(df,df2)

And here's the master data.frame:

master=data.frame(ID=c("B144", "B211", "B7090","B111", "B678", "B242", "V4322", "V2694", "V4399", "V543","V6577","V2", "V55", "V554", "V2009"),
    rename=c("S1","S2", "S3","N1","N2","S4","S5","N3","N4","N5","S6","S7","S8", "N6", "N7"))

Is there a way to rename the row names in the lists using this master?

Here's example output I want:

df <- data.frame(Value = c(1, 0, 6, 3, 4))
rownames(df) <- c("S1","S2","N2","N1", "S3")
df2 <- data.frame(Value = c(0, 0, 1, 4, 2))
rownames(df2) <- c("S7","N5","S6","S5", "S8")

List<-list(df,df2)

CodePudding user response:

The function is long in one line. So I define it separately for better readability:

func <- function (DF) {
  lookup <- match(row.names(DF), master$ID)
  row.names(DF) <- master$rename[lookup]
  DF
}

List <- lapply(List, func)
  • Related