【发布时间】:2014-01-08 01:14:59
【问题描述】:
我希望将一组预先编写的函数应用于数据帧中逐渐增大的数据子集。在这个例子中,预先编写的函数计算 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 行)的子组,然后是四行……依此类推……直到我到达数据框的末尾(在示例中,这将是一个包含第 1-6 行的子组,但很高兴知道如何将其应用于任何数据框)。
期望的输出:
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
我曾尝试这样做但没有成功,目前这超出了我的能力范围。任何建议将不胜感激!
【问题讨论】: