我有一组2D点存储在p:
x <- c(0, 1, 2, 3, 4)
y <- c(0, 1, 2, 3, 4)
p <- cbind(x,y)
Run Code Online (Sandbox Code Playgroud)
我需要计算每个连续点之间的距离,我计算距离的函数是hypotenuse(实际上我的问题有点不同,因为我有一个经度列表,纬度值,我需要distVincentyEllipsoid从geosphere包中使用).
hypotenuse <- function(p1,p2)
{
sqrt((p1[1]-p2[1])^2+(p1[2]-p2[2])^2)
}
Run Code Online (Sandbox Code Playgroud)
我想使用,diff但在我看来,我不能传递给diff自定义"差异"功能的功能,所以我的解决方案到现在为止如下:
distances <- c()
for(i in 2:nrow(p))
{
distances <- c(distances,hypotenuse(p[i,],p[i-1,]))
}
Run Code Online (Sandbox Code Playgroud)
我读了一个类似于R中的diff的迭代和滞后函数的问题,但不仅仅是区别?我尝试以这种方式使用包中的rollapply函数zoo:
library(zoo)
rollapply(p,width=1,FUN=hypotenuse)
Run Code Online (Sandbox Code Playgroud)
但我得到了错误
FUN错误(数据[posns],...):
缺少参数"p2",没有默认值
所以在我看来,FUN不能是二元函数.
是否可以使用该rollapply功能来解决我的问题?
以下是一些方法:
> # 1a
> sqrt(rowSums(diff(p)^2))
[1] 1.414214 1.414214 1.414214 1.414214
> # 1b
> sqrt(diff(p[, 1])^2 + diff(p[, 2])^2)
[1] 1.414214 1.414214 1.414214 1.414214
> # 2a
> library(zoo)
> rollapply(p, 2, dist, by.column = FALSE)
[1] 1.414214 1.414214 1.414214 1.414214
> # 2b
> rollapply(p, 2, function(x) unname(hypotenuse(x[1, ], x[2, ])), by.column = FALSE)
[1] 1.414214 1.414214 1.414214 1.414214
> # 2c
> rollapply(p, 2, function(x) sqrt(sum(diff(x)^2)), by.column = FALSE)
[1] 1.414214 1.414214 1.414214 1.414214
Run Code Online (Sandbox Code Playgroud)
增加:重新排列并添加到解决方案中.