2013-12-19 24 views
3

我希望在一個數據幀在尺寸逐漸增加一組預先編寫的函數適用於數據子集提高數據的子集。在這個例子中,預寫函數計算1)一系列數據點中每個連續的一對位置之間的距離,2)一系列數據點的總距離(步驟1的總和),3)直線在一系列數據點的開始和結束位置之間的距離以及4)直線距離(步驟3)和總距離(步驟2)之間的比率。我希望知道如何將這些步驟(以及相應的功能)應用於數據框架內增加大小的子組。以下是一些示例數據和預編寫的功能。如何將功能應用到數據幀

實施例的數據:

> dput(df) 
structure(list(latitude = c(52.640715, 52.940366, 53.267749, 
53.512608, 53.53215, 53.536443), longitude = c(3.305727, 3.103194, 
2.973257, 2.966621, 3.013587, 3.002674)), .Names = c("latitude", 
"longitude"), class = "data.frame", row.names = c(NA, -6L)) 

    Latitude Longitude 
1 52.64072 3.305727 
2 52.94037 3.103194 
3 53.26775 2.973257 
4 53.51261 2.966621 
5 53.53215 3.013587 
6 53.53644 3.002674 

預編寫的函數:

# Step 1: To calculate the distance between a pair of locations 
pairdist = sapply(2:nrow(df), function(x) with(df, trackDistance(longitude[x-1], latitude[x-1], longitude[x], latitude[x], longlat=TRUE))) 
# Step 2: To sum the total distance between all locations 
totdist = sum(pairdist) 
# Step 3: To calculate the distance between the first and end location 
straight = trackDistance(df[1,2], df[1,1], df[nrow(df),2], df[nrow(df),1], longlat=TRUE) 
# Step 4: To calculate the ratio between the straightline distance & total distance 
distrat = straight/totdist 

我想首先應用這種函數的子組僅前兩行(即行1- 2),然後到前三行(第1-3行)的子組,然後是四行......依此類推...直到我到達數據幀的末尾(在該示例中,這將是包含行的子組但是如果知道如何將其應用於任何數據幀將會很好)。

所需的輸出:

Subgroup Totdist Straight Ratio 
1   36.017  36.017  1.000     
2   73.455  73.230  0.997 
3  100.694  99.600  0.989 
4  104.492 101.060  0.967 
5  105.360 101.672  0.965 

我已經嘗試沒有成功做到這一點,目前這已經超出了我的能力。任何建議將非常感謝!

回答

2

有很多的優化可以做。

  • trackDistance()是向量化的,所以你不需要申請。
  • 要獲得計算總距離的矢量化方法,請使用cumsum()
  • 您只需計算一次成對距離。重新計算每次看到不同的子集時,都是浪費資源。因此,在構建函數時,請嘗試根據完整的數據框思考問題。

把一切在輸出所需的數據幀中的一個功能,你可以做類似的規定:

myFun <- function(x){ 
    # This is just to make typing easier in the rest of the function 
    lat <- x[["Latitude"]] 
    lon <- x[["Longitude"]] 
    nr <- nrow(x) 

    pairdist <-trackDistance(lon[-nr],lat[-nr], 
          lon[-1],lat[-1], 
          longlat=TRUE) 

    totdist <- cumsum(pairdist) 

    straight <- trackDistance(rep(lon[1],nr-1), 
          rep(lat[1],nr-1), 
          lon[-1],lat[-1], 
          longlat=TRUE) 

    ratio <- straight/totdist 
    data.frame(totdist,straight,ratio) 

} 

概念證明:

> myFun(df) 
    totdist straight  ratio 
1 36.01777 36.01777 1.0000000 
2 73.45542 73.22986 0.9969293 
3 100.69421 99.60013 0.9891346 
4 104.49261 101.06023 0.9671519 
5 105.35956 101.67203 0.9650005 

請注意,您可以添加額外的參數來定義緯度和經度列。並觀察您的大小寫,在您的問題中,您在數據框中使用谷歌縱橫,但在代碼中使用緯度(小1)。

+0

+1有另一個。很好的回答 –

+0

@ Joris:謝謝你的解決方案。這太棒了!正是我想要做的。非常感謝和聖誕快樂! – Emily