繁体   English   中英

函数返回R中的修改矩阵

[英]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对象,矩阵和数据帧。

赋值发生在函数的环境中,而不是全局的。 您需要在函数中返回结果,并使用函数调用进行分配。 尝试这个:

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

暂无
暂无

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

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