R - 如何找到每列的每个连续行之间的差异

时间:2017-02-04 22:02:39

标签: r

Date    FXDL.AED.USD    FXDL.ALL.USD    FXDL.AMD.USD    FXDL.ANG.USD  
03/01/2005  3.6726  92.1    484 1.779999971  
04/01/2005  3.6726  92.1    487 1.779999971  
05/01/2005  3.6725  94.5    490.5   1.779999971 
06/01/2005  3.6726  95.1    490.5   1.779999971 
07/01/2005  3.6725  95.3    493.5   1.779999971 
08/01/2005  NA  NA  NA  NA  
09/01/2005  NA  NA  NA  NA  
10/01/2005  3.6726  96.9    497.5   1.779999971  
11/01/2005  3.6725  97.2    502.5   1.779999971  

我在数据框中有多个列,上面是它的一小部分,我想找到每列的每个连续行之间的差异。例如,行3 - 2,行4 - 3,行5 - 4等中每列的值

我使用了以下代码:

x_diff <- x[-1,] - x[-nrow(x),] 

但这会出现错误,我认为这是因为在某些字段中存在NA术语但我希望在求和中也包含这些NA项,因此它可以简单地返回NA。

编辑:

structure(list(Weekday = c(1, 2, 3, 4, 5), Date = structure(c(1104710400, 
1104796800, 1104883200, 1104969600, 1105056000), class = c("POSIXct", 
"POSIXt"), tzone = "UTC"), FXDL.AED.USD = c("3.6726000000000001", 
"3.6726000000000001", "3.6724999999999999", "3.6726000000000001", 
"3.6724999999999999"), FXDL.ALL.USD = c("92.1", "92.1", "94.5", 
"95.1", "95.3"), FXDL.AMD.USD = c("484", "487", "490.5", "490.5", 
"493.5")), .Names = c("Weekday", "Date", "FXDL.AED.USD", "FXDL.ALL.USD", 
"FXDL.AMD.USD"), row.names = c(NA, 5L), class = c("tbl_df", "tbl", 
"data.frame"))

1 个答案:

答案 0 :(得分:0)

我们可以在tidyverse

中执行此操作
library(tidyverse)
df1 %>% 
    mutate_each(funs(c(NA, diff(as.numeric(.)))), 3:5)