maycca
maycca

Reputation: 4090

Extract longitudinal pixel values from raster.list, save to data frame

I have a list of rasters of the same location for multiple years. The change in pixel value over time represents the time series of pixel. To further analyses, I need to extract the values over time per every pixel, and store it in data frame, where row = #pixel, column = year

Dummy data:

library(raster)

# create raster data from scratch
# create empty raster
y1<-raster(ncol = 3, nrow = 3)

values(y1)<-1:9

projection(y1)<-CRS("+init=epsg:4326")

# create and diversify the rasters
y2<-y1+10
y3<-y1+20
y4<-y1+30

# make list of rasters
y.list<-list(y1, y2,y3,y4)

# plot all rasters at once
par(mfrow = c(2,2))

for(i in 1:length(y.list)) {
  plot(y.list[[i]])
}

How the dataframe should look like:


         y1  y2  y3  y4
pixel1   1   10  20  30
pixel2
...
pixel9   9   19  29  39

How to extract unique pixel values over time, and convert individual pixel data to data frame??

Upvotes: 1

Views: 334

Answers (1)

maycca
maycca

Reputation: 4090

I found a great answer here ! How to extract values from rasterstack with xy coordinates?

No need to put rasters into the list of rasters - just create raster stack !!

Than, just simply use raster::extract to create a time series of each pixel value over time !

the whole script:

library(raster)

# create raster data from scratch
# create empty raster
y1<-raster(ncol = 3, nrow = 3)

values(y1)<-1:9

projection(y1)<-CRS("+init=epsg:4326")

# recreate and diversify the rasters
y2<-y1+10
y3<-y1+20
y4<-y1+30

# create raster stack
# create raster stack
s<-stack(y1, y2, y3, y4)

# plot rasters
plot(s)

# extract raster values - return a matrix of values in each pixel
# row = pixel, column = layer (year)
mat <- raster::extract( s , 1:ncell(s) )

tadaaaa !!!!

> mat
  layer.1 layer.2 layer.3 layer.4
 [1,]       1      11      21      31
 [2,]       2      12      22      32
 [3,]       3      13      23      33
 [4,]       4      14      24      34
 [5,]       5      15      25      35
 [6,]       6      16      26      36
 [7,]       7      17      27      37
 [8,]       8      18      28      38
 [9,]       9      19      29      39

Upvotes: 1

Related Questions