user1256539
user1256539

Reputation:

How to read specific ascii format in R

I have an ascii file that has the following format:

  4 3 2 
 0.00 0.00 
 0.00
 0.00 0.00 
 0.00
 0.00 0.00 
 0.00
 0.00 0.00 
 0.00
 1.00 1.00
 1.00 
 1.00 1.00
 1.00
 1.00 1.00
 1.00
 1.00 1.00
 1.00

The first line (4 3 2) is the header. Number 2 represent the numbers of groups in the file (in this case two groups: first with all zero and the second with all one). Each group consist of 4 sub-groups of three values (two on the first row and one on the next line).

I would like to read such a file in a way that 4 represent the number of columns and 3 the number of rows of a matrix or something that I can use with filled.contour, keeping also the two sub-groups separated (different factor).

I'm trying to do this using the read.fwf function, but I'm facing some difficulties while trying to specify the widths option. The columns are not allocated in the right way.

Upvotes: 1

Views: 255

Answers (1)

agstudy
agstudy

Reputation: 121568

You can use scan here, and use the header row to create the right matrix:

text <- ' 4 3 2 
 0.00 0.00 
 0.00
 0.00 0.00 
 0.00
 0.00 0.00 
 0.00
 0.00 0.00 
 0.00
 1.00 1.00
 1.00 
 1.00 1.00
 1.00
 1.00 1.00
 1.00
 1.00 1.00
 1.00'
dd <- scan(textConnection(text))
matrix(dd[-c(1:3)],ncol=dd[1],nrow=dd[2]*dd[3],byrow=TRUE)

     [,1] [,2] [,3] [,4]
[1,]    0    0    0    0
[2,]    0    0    0    0
[3,]    0    0    0    0
[4,]    1    1    1    1
[5,]    1    1    1    1
[6,]    1    1    1    1

Upvotes: 2

Related Questions