简体   繁体   English

从r中的固定点零计算速度

[英]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. 我正在尝试在R中从数据帧中的加速度计算速度,其中第一个值固定为0。我想使用v = u + atvelocity[2:nrow(trial.data)]查找速度其中t为常数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. 我尝试使用第二行中的滞后,但是这给出的值为零,第3行中的值正确,后面的其他值也不正确。

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 : 速度是累积的加速度,因此请使用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. 请注意,速度矢量具有最后一个元素(恰好是0.022),在将其读入数据表时会被忽略,因为否则列的长度将不相等。 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. 上面的代码以u = 0开头,但是可以将u更改为任何其他起始速度,并且该代码将按预期工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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