Reputation: 757
I have a dataset which contains an acceleration and a time column. Within excel
I can use these to create a velocity metric. However, I can't seem to replicate the formula in R
as one step involves adding a cell to the previous cell in the data.
Within excel the formula is H5 = H4+(G5*(B5-B4))
which is calculating a difference in time between readings(B5-B4
), multiplying the result by acceleration (G5*(B5-B4)
) then adding the results to the starting velocity value which is always zero.
The first two steps are fine but I haven't found how to replicate the third
data %>%
mutate(
Time_diff = Time - lag(Time),
Accel_Time = Accel*Time_diff
)
Here is the dataset with expected velocity column also, I've skipped ahead slightly in the data here as the first 100 or so rows have a zero velocity reading.
> dput(head(data1, 20))
structure(list(Time = c(1.002, 1.004, 1.006, 1.008, 1.01, 1.012,
1.014, 1.016, 1.018, 1.02, 1.022, 1.024, 1.026, 1.028, 1.03,
1.032, 1.034, 1.036, 1.038, 1.04), Accel = c(-0.04, -0.04, -0.05,
-0.05, -0.04, -0.04, -0.05, -0.05, -0.05, -0.05, -0.05, -0.06,
-0.06, -0.06, -0.06, -0.06, -0.06, -0.06, -0.07, -0.06),
Velocity = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
Time_diff = c(NA, 0.002, 0.002, 0.002, 0.002, 0.002, 0.002, 0.002, 0.002, 0.002,
0.002, 0.002, 0.002, 0.002, 0.002, 0.002, 0.002, 0.002, 0.002, 0.002),
Accel_Time = c(NA, -0.0000800000000000001, -0.0001, -0.0001,
-0.0000800000000000001, -0.0000800000000000001, -0.0001, -0.0001,
-0.0001, -0.0001, -0.0001, -0.00012, -0.00012, -0.00012, -0.00012, -0.00012, -0.00012, -0.00012, -0.00014, -0.00012)),
row.names = c(NA, 20L), class = "data.frame")
Any advice on this would be appreciated, thanks
Upvotes: 0
Views: 1215
Reputation: 747
constructing the example data frame:
data1 <- data.frame(Time = c(1.002, 1.004, 1.006, 1.008, 1.01, 1.012, 1.014, 1.016, 1.018, 1.02, 1.022, 1.024, 1.026, 1.028, 1.03, 1.032, 1.034, 1.036, 1.038, 1.04), Accel = c(-0.04, -0.04, -0.05, -0.05, -0.04, -0.04, -0.05, -0.05, -0.05, -0.05, -0.05, -0.06, -0.06, -0.06, -0.06, -0.06, -0.06, -0.06, -0.07, -0.06))
data1$Time_diff <- c(0,data1$Time[-1] - data1$Time[-length(data1$Time)])
accel_time
:data1$accel_time <- data1$Time_diff * data1$Accel
data1$velocity <- cumsum(data1$accel_time)
one liner:
cumsum(c(0,data1$Time[-1] - data1$Time[-length(data1$Time)]) * data1$Accel)
Upvotes: 3