简体   繁体   English

减去 R 中的连续值

[英]subtracting consecutive values in R

Basically I have a data like this:基本上我有这样的数据:

Begin.Time..s.  1.039*** 3.133* 5.156 7.168 9.249 11.362             

End.Time..s.  1.383**  3.437  5.5  7.539 9.546 11.674

I would like to make the following operation:我想做以下操作:

3.133* - (1.383** - 1.039***)  

And then continue until the end of the data.然后继续直到数据结束。

Using the lag function from dplyr , we can do the following,使用dplyrlag函数,我们可以执行以下操作,

df$Begin[-1] - na.omit(dplyr::lag(df$End - df$Begin))
#[1]  2.789  4.852  6.824  8.878 11.065

DATA数据

dput(df)
structure(list(Begin = c(1.039, 3.133, 5.156, 7.168, 9.249, 11.362
), End = c(1.383, 3.437, 5.5, 7.539, 9.546, 11.674)), .Names = c("Begin", 
"End"), row.names = c(NA, -6L), class = "data.frame")

EDIT Based on @nicola's suggestion, a lighter approach would be编辑基于@nicola 的建议,更轻松的方法是

df1$Begin[-1]-(df1$End-df1$Begin)[-nrow(df1)]
#[1]  2.789  4.852  6.824  8.878 11.065

hope it may be useful from base R希望它可能对基础 R 有用

df1$Begin[2:length(df1$Begin)]-(df1$End[1:5]-df1$Begin[1:5])
[1]  2.789  4.852  6.824  8.878 11.065

data数据

copied from previous OP sotos从以前的 OP sotos 复制而来

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

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