Ben Tan
Ben Tan

Reputation: 11

Looping over dataframes in R to change column and row names

I'm trying to automate some code, dealing with several dataframes which I'm going to turn into LaTeX tables later on. I want to loop over six dataframes, drop the same columns from them, and rename all their columns and rows to the same standard names.

I've tried creating a basic for loop but it doesn't do anything to the dataframes (nor does it give an error).

row1 <- c(.5,.25,.75)
row2 <- c(.5,.25,.75)
df_1 <- data.frame(rbind(row1,row2))
row3 <- c(.5,.25,.75)
row4 <- c(.5,.25,.75)
df_2 <- data.frame(rbind(row3,row4))
tables <- list(df_1,df_2)
for (i in tables){ 
  rownames(i) <- c("row one","row two")
  colnames(i) <- c("col one","col two","col three")
}
print(df_1)

It's printing df1 without the row or column names I'm trying to assign in the loops. If I manually assign the rownames without the for loop, it works. Any ideas why?

Upvotes: 1

Views: 996

Answers (2)

warnbergg
warnbergg

Reputation: 552

Alternatively you can use a lapply to speed up the process and keep the list structure.

tables <- lapply(list(df_1, df_2), function (df) {
    rownames(df) <- c("row one","row two")
    colnames(df) <- c("col one","col two","col three")
    return (df)
}

# [[1]]
#         col one col two col three
# row one     0.5    0.25      0.75
# row two     0.5    0.25      0.75
#
# [[2]]
#         col one col two col three
# row one     0.5    0.25      0.75
# row two     0.5    0.25      0.75

or tables <- lapply(tables, 'dimnames<-', list(c("row one","row two"),c("col one","col two","col three"))), which is more concise (credit to @markus)

Upvotes: 1

markus
markus

Reputation: 26373

Try

for (i in seq_along(tables)){ 
  rownames(tables[[i]]) <- c("row one","row two")
  colnames(tables[[i]]) <- c("col one","col two","col three")
  }
print(tables)
#[[1]]
#        col one col two col three
#row one     0.5    0.25      0.75
#row two     0.5    0.25      0.75

#[[2]]
#        col one col two col three
#row one     0.5    0.25      0.75
#row two     0.5    0.25      0.75

Upvotes: 1

Related Questions