Name list of data frames from data frame

153 views Asked by At

I usually read a bunch of .csv files into a list of data frames and name it manually doing.

#...code for creating the list named "datos" with files from library 
# Naming the columns of the data frames
names(datos$v1r1)<-c("estado","tiempo","x1","x2","y1","y2")
names(datos$v1r2)<-c(...)
names(datos$v1r3)<-c(...)

I want to do this renaming operation automatically. To do so, I created a data frame with the names I want for each of the data frames in my datos list.

Here is how I generate this data frame:

pru<-rbind(c("UT","TR","UT+","TR+"),
            c("UT","TR","UT+","TR+"),
            c("TR","UT","TR+","UT+"),
            c("TR","UT","TR+","UT+"))

vec<-paste("v1r",seq(1,20,1),sep="")
tor<-paste("v1s",seq(1,20,1),sep="")


nombres<-do.call("rbind", replicate(10, pru, simplify = FALSE))

nombres_df<-data.frame(corrida=c(vec,tor),nombres)

Because nombres_df$corrida[1] is v1r1, I have to name the datos$v1r1 columns ("estado","tiempo", nombres_df[1,2:5]), and so on for the other 40 elements. I want to do this renaming automatically. I was thinking I could use something that uses regular expressions.

Just for the record, I don't know why but the order of the list of data frames is not the same as the 1:20 sequence (by this I mean 10 comes before 2,3,4...)

Here's a toy example of a list with a similar structure but fewer and shorter data frames.

toy<-list(a=replicate(6,1:5),b=replicate(6,10:14))
1

There are 1 answers

0
josliber On BEST ANSWER

You have a data frame where variable corridas is the name of the data frame to be renamed and the remaining columns are the desired variable names for that data frame. You could use a loop to do all the renaming operations:

for (i in seq_len(nrow(nombres_df))) {
  names(datos[[nombres_df$corridas[i]]]) <- c("estado","tiempo",nombres_df[i,2:length(nombres_df)])
}