Tagar
Tagar

Reputation: 14911

serializing reading multiple matrices into a single construction

In R, is it possible to rewrite following

iops1 <- read.csv('mytest_20141009_1755_iops.csv', skip=6)[2:21]
mbps1 <- read.csv('mytest_20141009_1755_mbps.csv', skip=6)[2:21]
lat1  <- read.csv('mytest_20141009_1755_lat.csv', skip=6)[2:21]

iops2 <- read.csv('mytest2_20141010_1034_iops.csv', skip=6)[2:21]
mbps2 <- read.csv('mytest2_20141010_1034_mbps.csv', skip=6)[2:21]
lat2  <- read.csv('mytest2_20141010_1034_lat.csv', skip=6)[2:21]

iops3 <- read.csv('mytest_20141011_2050_iops.csv', skip=6)[2:21]
mbps3 <- read.csv('mytest_20141011_2050_mbps.csv', skip=6)[2:21]
lat3  <- read.csv('mytest_20141011_2050_lat.csv', skip=6)[2:21]

Into something like (pseudo code)

[iops1,mbps1,lat1, iops2,mbps2,lat2, ... ]
 <- serial(read.csv, ('file1.csv','files2.csv','file3.csv',...), skip=6)[2:21]

I wrote my first R script and it works as expected, just looking around if it's possible to express some parts of it better. I know R has an efficient syntax. Thanks!

Upvotes: 0

Views: 43

Answers (1)

Jason
Jason

Reputation: 1569

I don't know how one would do specifically what you ask but you could write a loop to read in files and name them. I typically name my files that I'm going to read in in such as fashion as to allow me to loop through them. So if you can rename your 20141009_1755, 20141010_1034, and 20141011_2050 to 1,2,3 then the following works and you can loop through a large # of files. Otherwise you can still do below but with slightly amended code.

file.names<-c('iops','mbps','lat')
for (i in 1:3) {
    for (j in file.names) {
        file<-read.csv(paste0('mytest_',i,j,'.csv'),skip=6)[2:21]) #read in your file
        assign(paste0(j,i),file) #rename your dataframe
    }
}

Upvotes: 1

Related Questions