[GIS] Extracting point data for each lat and long from raster file into a dataframe

rraster

I have gridded data files ( see sample -each file consist of monthly precip and is label pYYYYMM) https://www.dropbox.com/sh/63z166tjxyu12s5/AAAs3Ccn1zdVoBYMj8Y1o303a?dl=0.

I am trying to extract the point data for each territories of Canada and so that i can get a time series for each lat and longitude within the dataset

library(raster)
files= list.files( ,pattern='*.grd',full.names=TRUE)
s <- stack(files)
# Setting Missing values 
s[s >= 170141000918782798866653488190622531584.00] <- NA_real_
# read in my point of interest, 
pt<- read.csv("latandlong")

This data is available https://www.dropbox.com/s/3p4u4pyxkyo2q15/latandlong.csv?dl=0

# Setting the data points to spatial value using the first two columns
point <- SpatialPoints(pt)
df1 <- extract(s, point, df=TRUE,method='simple')
write.csv(df1, 'precip.csv')
str(df1)
data.frame':    409 obs. of  1922 variables:
$ ID     : num  1 2 3 4 5 6 7 8 9 10 ...
$ t190001: num  -18.8 -19.6 -20.2 -20.8 -21.9 ...
$ t190002: num  -23 -23.4 -23.8 -24.8 -25.6 ...
$ t190003: num  -14 -14.4 -14.5 -15.3 -15.9 ...

When I run the extract function advised by RobertH, this work but I just need one final step. I also need the corresponding x-y values and lat / lat coordinates to be included in my dataframe as well or is there any way to extract data for each territories directly for each point.

Best Answer

I assume that with 'x' and 'y' you mean row and column number? If so, yo can do the following

# Your code (simplified)
library(raster)
files= list.files(pattern='\\.grd$', full.names=TRUE)
s <- stack(files)
pt<- read.csv("latandlong")
point <- SpatialPoints(pt)
df <- extract(s, point, df=TRUE, method='simple')

# get row and column number
row <- rowFromY(s, pt)
col <- colFromX(s, pt)

# combine
df <- cbind(df, pt, row=row, col=col)
head(df)