novicegeek
novicegeek

Reputation: 773

How do I read data from txt file to create a 2D matrix?

I am writing a function in R which reads a text file with some header information in the first 8 lines and then the actual data starts. Here is how the file looks:

Line 1 to
.....
Line 10 (header information)
0 0 4.169080e+000
1 0 6.391669e+000
2 0 6.391669e+000
.
.
.
511 0 9.922547e+000
0 1 5.268026e+000
1 1 5.268026e+000
.
.
.
511 511 9.922547e+000

I have extracted information from the lines which are part of the header. Line 9 onwards the line format is:

x y value

I want to read all these lines one by one (line 11 onwards) and form a 2D matrix(dimensions: 511 X 511) of the value column so that later I can generate an image using this. Can someone help me how I organize this in a matrix? I am trying to use a yLoop and a nested xLoop but it is not working.

Upvotes: 0

Views: 540

Answers (1)

Paulo E. Cardoso
Paulo E. Cardoso

Reputation: 5856

can't you just create a matrix with 511 lines?

v <- rnorm(511*511, 3, 1)
matrix(v, nrow = 511, ncol = 511)

for something smaller

v<- rnorm(4*4, 3,1)
> matrix(v, nrow = 4, ncol = 4)
         [,1]     [,2]     [,3]     [,4]
[1,] 1.944165 4.263226 2.700559 3.672780
[2,] 3.932594 1.742278 3.733877 3.115301
[3,] 5.224144 1.139828 2.979448 3.402496
[4,] 3.619015 4.248993 2.667306 2.168456

library(raster)
rv <- raster(matrix(v, nrow = 4, byrow = F)) # you'll want it with the default byrow = F
plot(rv)

plot raster

If you have something like this

x y v
0 0 4.169080e+000
1 0 6.391669e+000
2 0 6.391669e+000
511 0 9.922547e+000
0 1 5.268026e+000
1 1 5.268026e+000
511 511 9.922547e+000

and reading it just from the clipboard

v <- read.table(text=readClipboard(), header=T)

you'll get something like this

> d
    x   y        v
1   0   0 4.169080
2   1   0 6.391669
3   2   0 6.391669
4 511   0 9.922547
5   0   1 5.268026
6   1   1 5.268026
7 511 511 9.922547

and d$v will be you data to plot.

You can handle raster resolution and coordinate reference system.

You possibly have a reference layer x to read resolution and crs I suppose. If so, use something like

v <- matrix(d$v, nrow = 4, byrow = F)
rv <- raster(v, xmn=x@extent@xmin, ymn=x@extent@ymin,
             xmx=x@extent@xmax, ymx=x@extent@ymax,
             crs = CRS(proj4string(x)))

With your data:

myfolder <- 'D:/temp'
d <- read.table(file.path(myfolder, 'sample.txt'), header = F, skip = 9, sep = '')
> head(d)
  V1 V2 V3
1  0  0 12
2  1  0  7
3  2  0 10
4  3  0 11
5  4  0  8
6  5  0  9
rv <- raster(nrows=100, ncols=100)
rv[] <- matrix(d$V3, nrow = 100, byrow = F)
plot(rv)

plot rasterLayer

Considering that the image is 1 x 1mm, you could try

rv1 <- raster(matrix(d$V3, nrow = 100, byrow = T), # I'm changing how d$V3 is arranged
              xmn=0, ymn=0,
              xmx=1, ymx=1)
spplot(rv1, scales = list(draw = TRUE))

spplot

Upvotes: 1

Related Questions