簡體   English   中英

如何轉換循環以應用族函數以提高效率?

[英]How to convert loop to apply family function for efficiency?

我試圖基於是否有兩個已知的列都在一定距離之內添加一列,我能夠通過for循環來完成此操作,但是有很多行,因此需要花費數小時來執行。 我在將其轉換為應用功能以使其更高效時遇到麻煩

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)
}

正如馬庫斯所說:

您實際上不必遍歷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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM