【问题标题】:How to extract data from the points closer to required location in R?如何从靠近 R 中所需位置的点提取数据?
【发布时间】:2019-10-18 22:23:46
【问题描述】:

我有两个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))))

欢迎提出任何想法。

【问题讨论】:

  • 示例正确吗? “FakeData”的前 3 行名称是 GridsLongLat
  • @arkun,我更正了ExCor 数据框。我需要用来自FakeData 的数据填充这个数据框,这些数据要么匹配Long & Lat,要么从最近的FakeDataLong and lat 点获取数据。这有意义吗?
  • 那么为 DF2 中的每个点找到 DF1 中最近的点?试试 FNN 包。
  • 感谢@Spacedman,我会研究一下这个包以备将来使用。

标签: r dataframe coordinates data-extraction


【解决方案1】:

实现此目的的多种方法之一是在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')

【讨论】:

  • 谢谢@jbaums,在另存为CSV 之前有一个简单的选择transposenewdat
猜你喜欢
  • 2010-10-28
  • 1970-01-01
  • 1970-01-01
  • 2019-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-03
  • 1970-01-01
相关资源
最近更新 更多