-1

I want to extract a matrix data from THREE ".dat" files with file names x1,x2 and x3 and combine them in one matrix. ( I have merged them here for convenience but should be assumed from three files). Each file has 3x3 matrix data. I want to extract the data in each file with corresponding DATE on one column. So the result will have 4 columns and 9 rows. The date should be written on the first row of each matrix and the rest of the spaces can be filled with NA's or leave them. Here is the file:enter image description here

G1124E
  • 407
  • 1
  • 10
  • 20
  • 1
    You should provide a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) (pictures of data are not helpful). Describe where exactly you are having trouble (we're not here just to write code for you). Show the code you have attempted to write to solve the problem. – MrFlick Apr 28 '16 at 14:22
  • 1
    Do not use images. Use text so readers can copy and paste them. Also show expected output and show the code of your attempted solution. – G. Grothendieck Apr 28 '16 at 14:24
  • Try `files <- list.files(); lst <- lapply(files, read.csv, skip=3, header=FALSE); lst2 <- lapply(files, scan, skip=2, nlines=1); Datetime <- sub(".*:\\s+", "", unlist(lst2)); do.call(rbind, Map(`cbind`, lst, Datetime=Datetime))` – akrun Apr 28 '16 at 14:34

1 Answers1

1

Assuming that the files have 3 header lines before the beginning of data and if all the files are in the working directory. Get all the files from the working directory using list.files(). Loop through the 'files', read the dataset with read.csv, skip the first 3 lines, specifying the header as FALSE. Then, we third line from each of the files with scan, remove the substring until the date part with sub, create a column in each of the list element using Map, and rbind the output to have a single data.frame.

files <- list.files()
lst <- lapply(files, read.csv, skip=3, header=FALSE)
lst2 <- lapply(files, scan, skip=2, nlines=1, what = "")
Datetime <- sub(".*:\\s+", "", unlist(lst2))
do.call(rbind, Map(cbind, lst, Datetime=Datetime))
akrun
  • 874,273
  • 37
  • 540
  • 662