【问题标题】:The index of second, third,.. min with apply function具有应用功能的第二、第三、...分钟的索引
【发布时间】:2017-10-02 12:24:34
【问题描述】:

我有一个函数,我正在计算纬度/经度坐标(SpatialPoints)和另一个坐标向量(也在SpatialPoints)之间的最小距离的索引。我用来查找 min dist 的函数是:

library(rgeos)
dfdist$mindist <-apply(gDistance(sp1, sp2, byid=TRUE), 1, which.min)

上面的函数在我预先存在的数据框dfdist 中为我提供了一个列mindist,它是出现最小距离的点的行号的索引。

我还想找到第 2 分钟距离和第 3 分钟距离,但我不确定如何使用 apply() 执行此操作。 which.min 是否有替代品,它会给我第二分钟的索引?第三分钟?

【问题讨论】:

  • 也许将whichrank 结合起来?如:which(rank(your_data)==2)。不过要注意关系。

标签: r dataframe apply min


【解决方案1】:

您可以使用此用户定义的函数来执行此操作:

f_which.min <- function(vec, idx) sort(vec, index.return = TRUE)$ix[idx]

所以你可以使用:

apply(gDistance(sp1, sp2, byid=TRUE), 1, f_which.min, idx = 1) 

相应地设置参数idx。即idx=1第一分钟,idx=2第二分钟等等。

【讨论】:

  • 这太棒了。谢谢!
【解决方案2】:

我会使用如下函数:

which_nmin <- function(x, n = 1) 
{
  ux <- unique(x)
  ux <- ux[order(ux)][n]
  which(x == ux)
}

which_nmin(c(1, 1, 1, 1:5), 3)


which_nmax <- function(x, n = 1) 
{
  ux <- unique(x)
  ux <- ux[order(ux, decreasing = TRUE)][n]
  which(x == ux)
}

which_nmax(c(1, 1, 1, 1:5), 2)

您的apply 电话将是

apply(gDistance(sp1, sp2, byid=TRUE), 1, which_nmin, n = 2)

【讨论】:

  • 我不知道为什么,但这似乎最小化了我的坐标向量的纬度变化,但并没有最小化函数。我离其他坐标很远。这只是最小化一列吗?
  • 糟糕。这就是我仅在单调向量上进行测试所得到的。这些功能现已更正。
猜你喜欢
  • 2015-04-11
  • 2012-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多