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


i writing function in r reads text file header information in first 8 lines , actual data starts. here how file looks:

line 1 ..... 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 lines part of header. line 9 onwards line format is:

x y value 

i want read these lines 1 one (line 11 onwards) , form 2d matrix(dimensions: 511 x 511) of value column later can generate image using this. can me how organize in matrix? trying use yloop , nested xloop not working.

can't create matrix 511 lines?

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

for 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 default byrow = f plot(rv) 

plot raster

if have 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 clipboard

v <- read.table(text=readclipboard(), header=t) 

you'll 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 data plot.

you can handle raster resolution , coordinate reference system.

you possibly have reference layer x read resolution , crs suppose. if so, use 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 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 image 1 x 1mm, try

rv1 <- raster(matrix(d$v3, nrow = 100, byrow = t), # i'm changing how d$v3 arranged               xmn=0, ymn=0,               xmx=1, ymx=1) spplot(rv1, scales = list(draw = true)) 

spplot


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

android - Keyboard hides my half of edit-text and button below it even in scroll view -

css - Make div keyboard-scrollable in jQuery Mobile? -