如何转换循环以应用族函数以提高效率?

时间:2019-02-19 09:37:32

标签: r

我试图基于两个已知列是否在一定距离内来添加列,我能够通过for循环来完成此操作,但是行很多,因此需要花费数小时来执行。我在将其转换为Apply函数以使其更高效时遇到麻烦

for(i in 1:nrow(Current_Month){
    d = distm(c(90, 90), c(Current_Month$Lon[i], Current_Month$Lat[i]), fun=distHaversine)
    Current_Month$Nearby[i] = ifelse(d < 1000, 1, d)
}

1 个答案:

答案 0 :(得分:0)

马库斯说:

实际上,您不必遍历Current_Month-data.frame。

distm-函数还采用具有两列的矩阵(或data.frame)。

这对我有用一点虚拟样本数据。

Current_Month <- data.frame("Lon" = sample(1:100, 1000, replace = TRUE),
                            "Lat" = sample(1:90, 1000, replace = TRUE))

start <- Sys.time() 
d = distm(c(90, 90), Current_Month, fun=distHaversine)
end <- Sys.time()
end - start
> Time difference of 0.001993895 secs

In contrast to your:

start <- Sys.time()
for(i in 1:nrow(Current_Month)){
  d = distm(c(90, 90), c(Current_Month$Lon[i], Current_Month$Lat[i]),
      fun=distHaversine)
 }
end <- Sys.time()
end - start
Time difference of 0.2293599 secs

所以它要快得多。

然后继续:

Current_Month$Nearby = t(ifelse(d < 1000, 1, d)) #had to transpose this one though