如何从更接近 R 中所需位置的点中提取数据?

How to extract data from the points closer to required location in R?

我有两个data.frameFakeDataLong & Lat 和数据,而 ExCorLong & Lat 个点,我想从 FakeData 中提取数据。 ExCor 应该只从最近的点提取数据。 下面是一些样本数据

rm(list = ls())

DF1 = data.frame(t(data.frame(Grids = 1:5, Long = runif(5, min = 5, max = 10), Lat = runif(5, min = 2, max = 3))))
DF2 = data.frame(X1 = runif(1095, 0.5,1), X2 = runif(1095, 1.5,2), X3 = runif(1095, 0.5,1.5), X4 = runif(1095, 0.5,6), X5 = runif(1095, 0.5,15))
FakeData = rbind(DF1, DF2)

ExCor = data.frame(t(data.frame(Long = runif(3, 7, 9), Lat = runif(3, 2,3))))

欢迎任何想法。

实现此目的的众多方法之一是在 sf::st_join 中使用 st_nearest_feature 谓词。不过,首先,您需要重新调整数据结构,使其与处理空间几何的包更加兼容。

library(sf)

# Reshape datasets so that coords and attributes are columns, not rows
ExCor <- setNames(do.call(rbind.data.frame, ExCor), row.names(ExCor))
FakeData <- setNames(do.call(rbind.data.frame, FakeData), row.names(FakeData))

# Convert to sf objects
FakeData_sf <- st_as_sf(FakeData, coords=c('Long', 'Lat'))
ExCor_sf <- st_as_sf(ExCor, coords=c('Long', 'Lat'))

# Spatial join nearest feature
newdat <- st_join(ExCor_sf, FakeData_sf, join=st_nearest_feature)

如果需要,您可以再次写入 .csv...

st_write(newdat, 'newdat.csv', layer_options='GEOMETRY=AS_XY')