Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/77.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用R中的前一天值行进行减法?_R - Fatal编程技术网

如何使用R中的前一天值行进行减法?

如何使用R中的前一天值行进行减法?,r,R,原始数据: TRANS_DATE ID Value 10/2/2014 CPSG_CPM 2765.98 10/3/2014 CPSG_CPM 2840.76 10/6/2014 CPSG_CPM 3009.83 10/7/2014 CPSG_CPM 3025.05 10/8/2014 CPSG_CPM 2997.1 10/9/2014 CPSG_CPM 2946.08 10/10/2014 CPSG_CPM

原始数据:

TRANS_DATE  ID          Value
10/2/2014   CPSG_CPM    2765.98
10/3/2014   CPSG_CPM    2840.76
10/6/2014   CPSG_CPM    3009.83
10/7/2014   CPSG_CPM    3025.05
10/8/2014   CPSG_CPM    2997.1
10/9/2014   CPSG_CPM    2946.08
10/10/2014  CPSG_CPM    2977.12
10/13/2014  CPSG_CPM    2797.95
10/14/2014  CPSG_CPM    2805.27
10/15/2014  CPSG_CPM    2768.37
10/16/2014  CPSG_CPM    2699.4
10/17/2014  CPSG_CPM    2841.46
10/20/2014  CPSG_CPM    2876.85
我想添加另一列,它将为我提供上一个日期值的减去信息

TRANS_DATE  ID          Value     Diff
10/2/2014   CPSG_CPM    2765.98   74.78
10/3/2014   CPSG_CPM    2840.76   169.07
10/6/2014   CPSG_CPM    3009.83   15.22
10/7/2014   CPSG_CPM    3025.05   -27.95
10/8/2014   CPSG_CPM    2997.1    -51.02
10/9/2014   CPSG_CPM    2946.08   31.04
10/10/2014  CPSG_CPM    2977.12   -179.17
10/13/2014  CPSG_CPM    2797.95   7.32
10/14/2014  CPSG_CPM    2805.27   -36.9
10/15/2014  CPSG_CPM    2768.37   -68.97
10/16/2014  CPSG_CPM    2699.4    142.06
10/17/2014  CPSG_CPM    2841.46   35.39
10/20/2014  CPSG_CPM    2876.85 

这不是最优雅的解决方案,但它确实有效。需要将零作为
dx
的最后一个元素添加到
cbind
中,以将其添加到
data.frame

d = as.Date(c("10/2/2014","10/3/2014","10/6/2014","10/7/2014"),format="%m/%d/%Y")
x = c(2765.98,2840.76,3009.83,3025.05)

dx = diff(x)
dx = append(dx,0)
print(dx)

df = data.frame(d,x,dx)
View(df)

    d            x       dx
1   2014-10-02  2765.98 74.78
2   2014-10-03  2840.76 169.07
3   2014-10-06  3009.83 15.22
4   2014-10-07  3025.05 0.00