Home > Mobile >  How to write out from a matrix in R?
How to write out from a matrix in R?

Time:03-16

library(raster)
r <- raster(ncol=5, nrow=5, vals=2:26)
r1 <- raster(ncol=5, nrow=5, vals=2:26)
rs=stack(r,r1)
as.matrix(rs[[1]])
      [,1] [,2] [,3] [,4] [,5]
[1,]    2    3    4    5    6
[2,]    7    8    9   10   11
[3,]   12   13   14   15   16
[4,]   17   18   19   20   21
[5,]   22   23   24   25   26
as.matrix(rs[[2]])
    [,1] [,2] [,3] [,4] [,5]
[1,]    2    3    4    5    6
[2,]    7    8    9   10   11
[3,]   12   13   14   15   16
[4,]   17   18   19   20   21
[5,]   22   23   24   25   26

I want to write the results to a text file as

 c1   c2   c3  .....c25
 2   3   4   ... 26 
 2   3   4   ... 26  

 dim(rs)
 [1] 5 5 2

my real data

 dim (rs)
 5 5 500

CodePudding user response:

We can unstack and convert to vector

library(raster)
out <- do.call(rbind.data.frame, lapply(unstack(rs), as.vector))
names(out) <- paste0('c', seq_along(out))

-output

> out
  c1 c2 c3 c4 c5 c6 c7 c8 c9 c10 c11 c12 c13 c14 c15 c16 c17 c18 c19 c20 c21 c22 c23 c24 c25
1  2  3  4  5  6  7  8  9 10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26
2  2  3  4  5  6  7  8  9 10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26

and then write the data.frame into a csv file with write.csv

write.csv(out, 'yourfile.csv', quote = FALSE, row.names = FALSE)
  •  Tags:  
  • r
  • Related