我想创建一个脚本,使用移动窗口将函数应用于整个数据框中的空间点子集。
给定一个包含纬度位置列和经度位置列的数据矩阵,我想获得整个数据集中每 5 个连续位置的弯曲度测量值(即将该函数应用于从开始到结束的每组 5 个位置)。弯曲度是沿一系列点移动的实际距离与起点和终点之间移动的直线距离的比率。
示例数据:
df <- structure(list(IndexNo = 1:13, Latitude = c(52.363205, 52.640715,
52.940366, 53.267749, 53.512608, 53.53215, 53.536443, 53.553523,
53.546862, 53.55095, 53.571766, 53.587558, 53.592084), Longitude = c(3.433247,
3.305727, 3.103194, 2.973257, 2.966621, 3.013587, 3.002674, 3.004011,
2.98778, 2.995589, 3.004867, 3.003511, 2.999092)), .Names = c("IndexNo", "Latitude", "Longitude"), class = "data.frame", row.names=c(NA,-13L))
期望的输出:
IndexNo Latitude Longitude Sinuosity
1 52.36321 3.433247 NA
2 52.64072 3.305727 1.0085
3 52.94037 3.103194 1.0085
4 53.26775 2.973257 1.0085
5 53.51261 2.966621 1.0085
6 53.53215 3.013587 1.9392
7 53.53644 3.002674 1.9392
8 53.55352 3.004011 1.9392
9 53.54686 2.987780 1.9392
10 53.55095 2.995589 1.0669
11 53.57177 3.004867 1.0669
12 53.58756 3.003511 1.0669
13 53.59208 2.999092 1.0669
初始尝试(在用于计算 5 个位置的单个部分的弯曲度的代码中):
# To create a subset of the first 5 locations in the data frame
subset<- bird[1:5, c("Latitude", "Longitude","IndexNo")]
library(trip)
# To calculate the straight-line distance between the beginning and end point of a 5-point sequence
straightd<- trackDistance(subset[1,2], subset[1,1], subset[5,2], subset[5,1], longlat=TRUE)
# To calculate the distance between each pair of consecutive points (for a 5-point sequence)
d1<- trackDistance(subset[1,2], subset[1,1], subset[2,2], subset[2,1], longlat=TRUE)
d2<- trackDistance(subset[2,2], subset[2,1], subset[3,2], subset[3,1], longlat=TRUE)
d3<- trackDistance(subset[3,2], subset[3,1], subset[4,2], subset[4,1], longlat=TRUE)
d4<- trackDistance(subset[4,2], subset[4,1], subset[5,2], subset[5,1], longlat=TRUE)
# To return the actual distance between the beginning and end point of a 5-point sequence
actd<- sum(d1,d2,d3,d4)
# Function to calcualte the sinuosity (ratio between the actual distance and the straight-line distance)
sinuosity <- function (x, y) {
x/y
}
new <- sinuosity(actd, straightd)
# To add a sinuosity column to the 5 rows of locations on which the sinuosity index was measured
subset$Sinuosity <- rep(new, nrow(subset))