gpt4 book ai didi

r - 是否可以将自定义差异函数传递给 R 的差异函数?

转载 作者:行者123 更新时间:2023-12-04 10:43:22 25 4
gpt4 key购买 nike

我在 p 中存储了一组二维点:

x <- c(0, 1, 2, 3, 4)
y <- c(0, 1, 2, 3, 4)
p <- cbind(x,y)

我需要计算每个连续点之间的距离,我计算距离的函数是 hypotenuse(实际上我的问题有点不同,因为我有一个经度、纬度值列表,我需要使用 geosphere 包中的 distVincentyEllipsoid

hypotenuse <- function(p1,p2)
{
sqrt((p1[1]-p2[1])^2+(p1[2]-p2[2])^2)
}

我想使用 diff 但在我看来我无法将自定义“差异”函数传递给 diff 函数,所以我的解决方案到现在是以下内容:

distances <- c()
for(i in 2:nrow(p))
{
distances <- c(distances,hypotenuse(p[i,],p[i-1,]))
}

我阅读了问题 A iterative and lagging function similar to diff in R, but not just difference?我尝试以这种方式使用 zoo 包中的 rollapply 函数:

library(zoo)
rollapply(p,width=1,FUN=hypotenuse)

但是我得到了错误

Error in FUN(data[posns], ...) :
argument "p2" is missing, with no default

所以在我看来 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

添加:重新排列并添加到解决方案中。

关于r - 是否可以将自定义差异函数传递给 R 的差异函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20906674/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com