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
我已經嘗試沒有成功做到這一點,目前這已經超出了我的能力。任何建議將非常感謝!
+1有另一個。很好的回答 –
@ Joris:謝謝你的解決方案。這太棒了!正是我想要做的。非常感謝和聖誕快樂! – Emily