简体   繁体   中英

R Plyr Rename multiple columns in list of dataframes

Only just discovered Plyr and it has saved me a tonne of lines combining multiple data frames which is great. BUT I have another renaming problem I cannot fathom.

I have a list, which contains a number of data frames (this is a subset as there are actually 108 in the real list).

> str(mydata)
List of 4
 $ C11:'data.frame':    8 obs. of  3 variables:
  ..$ X                  : Factor w/ 8 levels "n >= 1","n >= 2",..: 1 2 3 4 5 6 7 8
  ..$ n.ENSEMBLE.COVERAGE: num [1:8] 1 1 1 1 0.96 0.91 0.74 0.5
  ..$ n.ENSEMBLE.RECALL  : num [1:8] 0.88 0.88 0.88 0.88 0.9 0.91 0.94 0.95
 $ C12:'data.frame':    8 obs. of  3 variables:
  ..$ X                  : Factor w/ 8 levels "n >= 1","n >= 2",..: 1 2 3 4 5 6 7 8
  ..$ n.ENSEMBLE.COVERAGE: num [1:8] 1 1 1 1 0.96 0.89 0.86 0.72
  ..$ n.ENSEMBLE.RECALL  : num [1:8] 0.91 0.91 0.91 0.91 0.93 0.96 0.97 0.98
 $ C13:'data.frame':    8 obs. of  3 variables:
  ..$ X                  : Factor w/ 8 levels "n >= 1","n >= 2",..: 1 2 3 4 5 6 7 8
  ..$ n.ENSEMBLE.COVERAGE: num [1:8] 1 1 1 1 0.94 0.79 0.65 0.46
  ..$ n.ENSEMBLE.RECALL  : num [1:8] 0.85 0.85 0.85 0.85 0.88 0.9 0.92 0.91
 $ C14:'data.frame':    8 obs. of  3 variables:
  ..$ X                  : Factor w/ 8 levels "n >= 1","n >= 2",..: 1 2 3 4 5 6 7 8
  ..$ n.ENSEMBLE.COVERAGE: num [1:8] 1 1 1 1 0.98 0.95 0.88 0.74
  ..$ n.ENSEMBLE.RECALL  : num [1:8] 0.91 0.91 0.91 0.91 0.92 0.94 0.95 0.98

What I really want to achieve is for each data frame to have the columns prepended with the title of the dataframe. So in the example the columns would be:

C11.X , C11.n.ENSEMBLE.COVERAGE & C11.n.ENSEMBLE.RECALL

C12.X , C12.n.ENSEMBLE.COVERAGE & C12.n.ENSEMBLE.RECALL

C13.X , C13.n.ENSEMBLE.COVERAGE & C13.n.ENSEMBLE.RECALL

C14.X , C14.n.ENSEMBLE.COVERAGE & C14.n.ENSEMBLE.RECALL

Can anyone suggest an elegant approach to renaming columns like this?

Here's a reproducible example using the iris data set:

# produce a named list of data.frames as sample data:
dflist <- split(iris, iris$Species)
# store the list element names:
n <- names(dflist)
# rename the elements:
Map(function(df, vec) setNames(df, paste(vec, names(df), sep = ".")), dflist, n)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM