2017-08-11 22 views
0

我已經從我的GPS跟蹤器導入數據,並且試圖找出如何在給定時間(例如12分鐘)或最佳時間給予處罰(例如5英里)。由於觀測的在不同的時間間隔,我的速度也不是恆定的,我都會有數據,如下面的表格:計算給定時間的最遠距離或給定距離的最佳時間

x <- read.table(header=T, sep="", stringsAsFactors = FALSE,text=" 
time dist 
4 3 
5 4 
5 6 
3 2 
5 5 
4 5 
4 3 
4 2 
5 6") 

我迄今爲止最好的嘗試就是次去了一個時間單位,以產生新的數據集。然後在給定時間內計算最遠距離相對容易。其缺點是a)我需要重複相同的邏輯以獲得最佳時間(以單位距離生成數據),b)對於具有數千個數據點的數據,似乎是相當次優的解決方案。

# Generate data frame where each row represents one unit of time 
z_adj <- data.frame(
    time = unlist(sapply(x$time, function(s) rep(s, each = s))), 
    dist = unlist(sapply(seq_along(x$dist), function(s) rep(x$dist[s], each = x$time[s]))) 
) 

z_adj$seq_time <- seq_along(z_adj$time) 
z_adj$time_dist <- z_adj$dist/z_adj$time 

# Furthest distance given time 
# Time 10 
z_adj$in_t10 <- sapply(z_adj$seq_time, function(s) sum(z_adj$dist[s:(s+9)])) 
z_adj$in_t10[which(z_adj$in_t10 == max(z_adj$in_t10, na.rm = T))] 
# Fastest time given distance 
# ... would need to do the above again with constant distance :/ 

有沒有更直接的方法來實現這個目標?

+0

有關我的答案的任何意見? –

回答

0

你可以使用這樣的事情:

x <- read.table(header=T, sep="", stringsAsFactors = FALSE,text=" 
time dist 
4 3 
5 4 
5 6 
3 2 
5 5 
4 5 
4 3 
4 2 
5 6") 

# Add starting point and cumulatice time/distance 
x <- rbind(c(0,0), x) 
x$total_time <- cumsum(x$time) 
x$total_dist <- cumsum(x$dist) 

# function to interpolate and calculate lagging differences 
foo <- function(x, y, n) { 
    interpolation <- approx(x, y, xout = seq(min(x), max(x))) 
    diff(interpolation$y, lag = n) 
} 

# Max distance in ten units of time 
max(foo(x$total_time, x$total_dist, 10)) 
# Min time for ten units of distance 
min(foo(x$total_dist, x$total_time, 10)) 

順便說一句,在你的代碼,你應該總結過z_adj$time_dist而不是z_adj$dist以得到正確的結果。