解释
根据
diff
x
必须是
x : a numeric vector or matrix containing the values to be differenced.
返回一个eplty数据框如果
是数据帧。
IMO最佳方法
我认为在中使用日期列没什么意义
. 所以。我可能会遵循以下方法。
rownames(df) <- df$Date
diff(as.matrix(df[, - 1]), lag = 1)
# converr to a matrix and apply diff
diff_mat <- diff(as.matrix(df[, - 1]), lag = 1)
# convert back to dataframe and set the Date column
diff_df <- as.data.frame(diff_mat)
diff_df$Date <- diff_df$Date
# now plot function should work
将日期向量转换为数字,然后转换为diff中的矩阵
df$Date <- as.numeric(df$Date)
diff(as.matrix(df), 1, 2)
# Date Per.Change Domestic.Production.from.UKCS Import Per.GDP.Growth
# [1,] -1 8.47 0.16 0.92 -0.5
# [2,] 1 -1.01 -0.03 -3.68 2.3
# [3,] 0 -3.47 -0.44 -0.48 -1.7
# [4,] -3 -1.77 0.59 2.15 0.3
# Average.Temperature Price.Electricity Price.Gas
# [1,] 0.03 8.73 8.94
# [2,] 8.31 -21.23 -18.88
# [3,] -1.18 7.64 4.04
# [4,] -1.94 6.90 8.89
创建数据
df <- read.table(text = "Date Per.Change Domestic.Production.from.UKCS Import Per.GDP.Growth Average.Temperature Price.Electricity Price.Gas
2010-10-01 2.08 3.54 5.40 0.2 10.44 43.50 46.00
2010-11-01 -3.04 3.46 6.74 -0.1 5.52 46.40 49.66
2010-12-01 0.31 3.54 9.00 -0.9 0.63 58.03 62.26
2011-01-01 2.65 3.59 7.58 0.6 4.05 48.43 55.98
2011-02-01 1.52 3.20 5.68 0.4 6.29 46.47 53.74
2011-03-01 -1.38 3.40 5.93 0.5 6.59 51.41 60.39",
header = T, sep ="")
df$Date <- as.Date(df$Date)