R 中 return 修改矩阵的函数

Function to return modified matrix in R

以下代码将向量 XTS1$XTSSum2 添加到 xts 对象 XTS1:

library(xts)
XTS1 <- structure(c(12, 7, 7, 22, 24, 30, 26, 23, 27, 30), .indexCLASS = c("POSIXct", "POSIXt"), .indexTZ = "", tclass = c("POSIXct", "POSIXt"), tzone = "", class = c("xts", "zoo"), .CLASS = structure("double", class = "CLASS"), formattable = structure(list(formatter = "formatC", format = structure(list(format = "f", digits = 2), .Names = c("format", "digits")), preproc = "percent_preproc", postproc = "percent_postproc"), .Names = c("formatter", "format", "preproc", "postproc")), index = structure(c(1413981900, 1413982800, 1413983700, 1413984600, 1413985500, 1413986400, 1413987300, 1413988200, 1413989100, 1413990000), tzone = "", tclass = c("POSIXct", "POSIXt")), .Dim = c(10L, 1L))
colnames(XTS1) <- "XTS1"
XTS1$XTSSum2 <- XTS1$XTS1 + lag(XTS1$XTS1,1)

以下函数执行相同的操作。

addfunction <- function(x){
  x$XTSSum2 <- x$XTS1 + lag(x$XTS1,1)
}
addfunction(XTS1)

但是向量XTS1$XTSSum2没有被存储。 我怎样才能让 addfunction 存储向量,以便在 运行 addfunction(XTS1) 之后,XTS1 看起来像这样:

                     XTS1 XTSSum2
2014-10-22 08:45:00   12      NA
2014-10-22 09:00:00    7      19
2014-10-22 09:15:00    7      14
2014-10-22 09:30:00   22      29
2014-10-22 09:45:00   24      46
2014-10-22 10:00:00   30      54
2014-10-22 10:15:00   26      56
2014-10-22 10:30:00   23      49
2014-10-22 10:45:00   27      50
2014-10-22 11:00:00   30      57

可重现的示例使用 xts 对象,假设同样的解决方案适用 到 xts 对象、矩阵和数据框。

赋值发生在函数的环境中,而不是全局环境中。您需要 return 函数中的结果,并在函数调用中对其进行赋值。试试这个:

addfunction <- function(x){
  x$XTSSum2 <- x$XTS1 + lag(x$XTS1,1)
  x
}
XTS1 <- addfunction(XTS1)