R 如何将函数应用于数据帧中增加的数据子集
我希望将一组预先编写的函数应用于数据帧中逐渐增大的数据子集。在此示例中,预写函数计算1)一系列数据点中每一连续位置对之间的距离,2)一系列数据点的总距离(步骤1的总和),3)一系列数据点的起点和终点位置之间的直线距离,以及4)直线距离(步骤3)与总距离(步骤2)之间的比率。我想知道如何将这些步骤(以及类似的函数)应用于数据帧中不断增大的子组。下面是一些示例数据和预先编写的函数 示例数据:R 如何将函数应用于数据帧中增加的数据子集,r,function,iteration,R,Function,Iteration,我希望将一组预先编写的函数应用于数据帧中逐渐增大的数据子集。在此示例中,预写函数计算1)一系列数据点中每一连续位置对之间的距离,2)一系列数据点的总距离(步骤1的总和),3)一系列数据点的起点和终点位置之间的直线距离,以及4)直线距离(步骤3)与总距离(步骤2)之间的比率。我想知道如何将这些步骤(以及类似的函数)应用于数据帧中不断增大的子组。下面是一些示例数据和预先编写的函数 示例数据: > dput(df) structure(list(latitude = c(52.640715, 5
> 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
我尝试过这样做,但没有成功,目前这超出了我的能力。任何建议都将不胜感激!可以进行大量优化
是矢量化的,因此您无需申请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)
}
请注意,您可以添加额外的参数来定义纬度和经度列。请注意大小写。在您的问题中,您在数据框中使用纬度,但在代码中使用纬度(小l)。@Joris:感谢您提供此解决方案。这太棒了!正是我想要做的。非常感谢,圣诞快乐!
> 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