Reputation: 33
I have one raster, and the location of the weather station. So that I want to extract single pixel value from my raster corresponds to weather station location. I tried different ways but I am not getting exact pixel value when I am cross-checked with ArcMap. Can someone please help how to get the exact pixel value? Thank you
Upvotes: 3
Views: 1454
Reputation: 47146
Example data
library(raster)
f <- system.file("external/test.grd", package="raster")
r <- raster(f)
If you want to get the value(s) for the a particular location you can do
station <- cbind(179735, 331230)
extract(r, station)
# 259.9123
Or first compute the cell number(s), and use that as index
i <- cellFromXY(r, station)
i
#[1] 5554
r[i]
# 259.9123
As to your follow up question (you should have asked a new question) "How can I extract surrounding nine-pixel average values from that location?"
Get the adjacent cells and extract
j <- adjacent(r, i, 8, pairs=F, include=T)
j
#[1] 5554 5473 5553 5633 5475 5555 5635 5474 5634
r[j]
#[1] 259.9123 273.5190 267.6167 218.8983 273.3555 252.1958 217.1910 274.5584
#[9] 223.2197
If you many locations
stations <- rbind(cbind(179735, 331230), cbind(179061, 330212))
cells <- cellFromXY(r, stations)
# get adjacent values but set "pairs" to TRUE
adj <- adjacent(r, cells, 8, pairs=TRUE, include=TRUE, sorted=TRUE)
vadj <- r[ adj[,2] ]
Now use tapply
or aggregate to get the mean
v <- tapply(vadj, adj[,1], mean)
v
# 5554 7537
#251.1630 412.0748
Upvotes: 4