2

I currently have a list of PC values for each row and column of a raster. I would like an output that looks like this:

x     y     PC
1    500    -3.45
1    501    -2.8

Here, x and y stand for row number and column number.

I am using the current code in R, but I end up obtaining a matrix only.

r <- pre_pca$map$PC1
r
class       : RasterLayer 
dimensions  : 339, 246, 83394  (nrow, ncol, ncell)
resolution  : 0.04166667, 0.04166667  (x, y)
extent      : 72.45833, 82.70833, 8.083333, 22.20833  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +ellps=WGS84 +towgs84=0,0,0,0,0,0,0 +no_defs 
data source : in memory
names       : PC1 
values      : -9.283828, 3.889567  (min, max)

s <- getValues(r, format="matrix")
head(s)


  X1       X2       X3       X4       X5       X6       X7       X8       X9      X10      X11
 1 NA       NA       NA 3.121756 3.056287 3.030809       NA 2.977990 2.954814 2.869022 2.802258
 2 NA       NA 3.154253 3.116532 3.023211 2.984813 2.973805 2.917697 2.896259 2.795462 2.754197
 3 NA       NA 3.079315 3.038321 2.985467 2.923184 2.909316 2.853848 2.858537 2.767026 2.749681
 4 NA       NA 3.083964 2.983488 2.948048 2.915955 2.879146 2.859355 2.748576 2.760476 2.724777

I have shown only the first 4 rows and x number of columns, but I would not want an output like this. In addition, please help removing NAs as well.

1

Looks like I found the answer in the reshape package in R

library(reshape2)
s <- melt(s)

> str(s)
'data.frame':   83394 obs. of  3 variables:
 $ X1   : int  1 2 3 4 5 6 7 8 9 10 ...
 $ X2   : int  1 1 1 1 1 1 1 1 1 1 ...
 $ value: num  NA NA NA NA NA NA NA NA NA NA ...

Using complete.cases in the base package in R, I kept only those rows that did not have any NAs.

s <- s[complete.cases(s),]
>str(s)

'data.frame':   54207 obs. of  3 variables:
 $ X1   : int  5 6 7 8 2 3 4 5 6 7 ...
 $ X2   : int  2 2 2 2 3 3 3 3 3 3 ...
 $ value: num  3.05 2.98 2.91 2.89 3.15 ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.