简体   繁体   中英

R extract variable from multiple dataframe in loop

I have a lot of result from parametric study to analyze. Fortunately there is an output file where the output file are saved. I need to save the name of file. I used this routine:

IndexJobs<-read.csv("C:/Users/.../File versione7.1/
  "IndexJobs.csv",sep=",",header=TRUE,stringsAsFactors=FALSE)

dir<-IndexJobs$WORKDIR
Dir<-gsub("\\\\","/",dir)
Dir1<-gsub(" C","C",Dir)

Now I use e for in order to read CSV and create different dataframe

for(i in Dir1){
  filepath <- file.path(paste(i,"eplusout.csv",sep=""))
  dat<-NULL
  dat<-read.table(filepath,header=TRUE,sep=",")
  filenames <- substr(filepath,117,150)
  names <-substr(filenames,1,21)
  assign(names, dat)
  }

Now I want to extract selected variables from each database, and putting together each variable for each database into separated database. I would also joint name of variable and single database in order to have a clear database for making some analysis. I try to make something but with bad results. I tried to insert in for some other row:

 for(i in Dir1){
  filepath <- file.path(paste(i,"eplusout.csv",sep=""))
  dat<-NULL
  dat<-read.table(filepath,header=TRUE,sep=",")
  filenames <- substr(filepath,117,150)
  names <-substr(filenames,1,21)
  assign(names, dat)
  datTest<-dat$X5EC132.Surface.Outside.Face.Temperature..C..TimeStep.
  nameTest<-paste(names,"_Test",sep="")
  assign(nameTest,datTest)
  DFtest=c[,nameTest]
}

But for each i there is an overwriting of DFtest and remain only the last database column.

Some suggestion?Thanks

Maybe it will work if you replace DFtest=c[,nameTest] with

DFtest[nameTest] <- get(nameTest)

or, alternatively,

DFtest[nameTest] <- datTest

This procedure assumes the object DFtest exists before you run the loop.


An alternative way is to create an empty list before running the loop:

DFtest <- list()

In the loop, you can use the following command:

DFtest[[nameTest]] <- datTest

After the loop, all values in the list DFtest can be combined using

do.call("cbind", DFtest)

Note that this will only work if all vectors in the list DFtest have the same length.

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