我有每天多个位置的动物 GPS 数据,并且定期间隔几天没有记录动物的位置。此外,我还有 16 天间隔的卫星数据。我现在想要 提取像素值 对应于 具体点 并致 特定的时间.

这意味着如果记录了动物的位置,例如我想在拍摄卫星图像前 2 天提取该图像(之后的图像)的像素值,而不是从记录动物位置前 14 天拍摄的图像中提取像素值。我总是想从时间更近的图像中提取出来。

我创建了一些测试数据,希望能够说明问题:

library(sp)
library(raster)

### Create test data
# create first raster
edc2012001_m <- raster(ncol=36, nrow=18)
edc2012001_m[] <- sample(1:ncell(edc2012001_m))

# create second raster
edc2012017_m <- raster(ncol=36, nrow=18)
edc2012017_m[] <- sample(1:ncell(edc2012017_m))

rasters<-stack(edc2012001_m,edc2012017_m)

# Create xy coordinates
time<-c("2012-01-01", "2012-01-01", "2012-01-01", "2012-01-02", "2012-01-02", "2012-01-02", "2012-01-12", "2012-01-12", "2012-01-13", "2012-01-13")
x <- rep(-50,10)
y <- sample(c(-80:80), 10)
data<-data.frame(x,y,time)

# Convert data to spatial points data frame
coordinates(data) <- c("x","y")

### Extract all data from raster stack
extract(rasters, data)

第一个栅格名称中的数字字符串表明该图像是在 2012 年的第一天拍摄的,第二个图像是在今年的 17 天拍摄的。

例如,测试数据中的第七个位置现在应从第二个光栅文件中提取,因为它根据时间更接近。

总而言之,我有 87 个栅格文件和 600 个观测值。我真的不知道如何编程。我想我可以用 substr() 从栅格名称检索日期信息。但除此之外...我很感谢我能得到的每一个提示,以及在这种情况下可能有用的功能。

有帮助吗?

解决方案

从你的最后一行开始

### Extract all data from raster stack
ex <- extract(rasters, data)

# assuming you have these names or something similar
x <- c("edc2012001_m", "edc2012017_m")
year <- as.integer(substr(x, 4, 7))
# day of year
doy <- as.integer(substr(x, 8, 10))
date <- as.Date(doy, origin=paste(year-1, "-12-31", sep=''))
time <- as.Date(time)

# time difference
dif <- t(apply(matrix(as.integer(time)), 1, function(x) x-as.integer(date)))

# smallest time difference
i <- apply(abs(dif), 1, which.min)

# combine rows and columns to select values
v <- ex[cbind(1:nrow(ex),i)]

我明白了

> i
 [1] 1 1 1 1 1 1 2 2 2 2
> v
 [1] 582 578 303 201 201 200 461 329 445 211
> 
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top