简体   繁体   中英

Calculating velocity from a fixed point zero in r

I am trying to calculate in R the velocity from acceleration in a data frame where the first value is fixed at 0. I would like to use v=u+at to find the velocity from velocity[2:nrow(trial.data)] where t is a constant 0.002. The initial data frame looks like this:

trial.data <- data.table("acceleration" = sample(-5:5,5), "velocity" = c(0))

     acceleration velocity
 1         0        0
 2         5        0
 3        -1        0
 4         3        0
 5         4        0

I have tried using lag from the second row however this gives a value of zero with the correct value in row 3 with other values following also being incorrect.

trial.data$velocity[2:nrow(trial.data)] = 
  (lag(trial.data$velocity,default=0)) + trial.data$acceleration * 0.002

      acceleration velocity
1           0       0.000
2           5       0.000
3          -1       0.010
4           3      -0.002
5           4       0.006

Velocity is accumulated acceleration, so use cumsum :

trial.data <- data.table("acceleration" = c(0,5,-1,3,4))
u <- 0 #starting velocity
velocity <- c(u,u+cumsum(trial.data$acceleration)*0.002)
trial.data$velocity <- velocity[-length(velocity)]

Output:

> trial.data
   acceleration velocity
1:            0    0.000
2:            5    0.000
3:           -1    0.010
4:            3    0.008
5:            4    0.014

Note the the velocity vector had a final element (which happens to be 0.022) which was neglected when reading it into the data table, since otherwise the columns would be of unequal length. The above code starts with u = 0 , but the u could be changed to any other starting velocity and the code would work as intended.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM