我有一个包含 400 多张卫星图像的文件夹,其名称如下:
filenames <- c("mosaic_NDVI_2000_10_15.tif", "mosaic_NDVI_2000_10_31.tif", "mosaic_NDVI_2000_11_16.tif", "mosaic_NDVI_2000_12_18.tif", "mosaic_NDVI_2000_12_2.tif", "mosaic_NDVI_2000_7_27.tif")
然后,我有一个数据集,需要在最近的日期提取 NDVI 的点坐标,但要做到这一点,我需要将文件名最接近的日期与行日期相匹配。
# example data
df <- data.frame(date = c("2000-7-26", "2000-10-20", "2000-12-10"), lon = c(23.05, 23.12, 23.08), lat = c(-32.56, -32.61, -32.53))
df$date <- lubridate::as_date(df$date)
filenames <- c("mosaic_NDVI_2000_10_15.tif", "mosaic_NDVI_2000_10_31.tif", "mosaic_NDVI_2000_11_16.tif", "mosaic_NDVI_2000_12_18.tif", "mosaic_NDVI_2000_12_2.tif", "mosaic_NDVI_2000_7_27.tif")
### NEED SOME CODE HERE TO EXTRACT THE DATES AND CREATE THE FOLLOWING VECTOR ###
filename_dates <- c("2000-10-15", "2000-10-31", "2000-11-16", "2000-12-18", "2000-12-2", "2000-7-27")
filename_dates <- lubridate::as_date(filename_dates)
for(i in 1:nrow(df)){
date <- df$date[i]
index <- which(abs(filename_dates - date) == min(abs(filename_dates - date)))
extraction_filename <- filenames[index]
point_vec <- vect(df[1,], geom=c("lon", "lat"), crs="+proj=longlat +datum=WGS84", keepgeom=FALSE)
NDVI <- rast(extraction_filename)
crs(NDVI) <- crs(point_vec)
value <- terra::extract(x=NDVI, y=point_vec, df=TRUE)
df$NDVI[i] <- value[2]}
将文件名转换为数据框并将两者中的日期转换为 Date 类。然后执行指定的 SQL 语句来连接最近的元素。
library(lubridate)
library(sqldf)
filenamesDF <- data.frame(date = ymd(trimws(filenames, whitespace = "\\D")))
df <- transform(df, date = ymd(date))
DF <- sqldf("select a.date, df.date, df.lon, df.lat
from filenamesDF as a left join df
on abs(a.date - df.date) = (select min(abs(a.date - df.date)) from df)")
names(DF)[2] <- "date2"
DF
给予
date date2 lon lat
1 2000-10-15 2000-10-20 23.12 -32.61
2 2000-10-31 2000-10-20 23.12 -32.61
3 2000-11-16 2000-12-10 23.08 -32.53
4 2000-12-18 2000-12-10 23.08 -32.53
5 2000-12-02 2000-12-10 23.08 -32.53
6 2000-07-27 2000-07-26 23.05 -32.56
问题的输入
filenames <- c("mosaic_NDVI_2000_10_15.tif", "mosaic_NDVI_2000_10_31.tif",
"mosaic_NDVI_2000_11_16.tif", "mosaic_NDVI_2000_12_18.tif",
"mosaic_NDVI_2000_12_2.tif", "mosaic_NDVI_2000_7_27.tif")
df <- data.frame(date = c("2000-7-26", "2000-10-20", "2000-12-10"),
lon = c(23.05, 23.12, 23.08),
lat = c(-32.56, -32.61, -32.53)
)