簡體   English   中英

如何在 XTS 中創建動態列

[英]How to create dynamic columns in XTS

想象一下,我有一個名為 SP500 的 XTS 對象,我想創建這樣的新列:

SP500$Cierre1 = lag(SP500$Cierre, k=1)
SP500$Cierre2 = lag(SP500$Cierre, k=2)
SP500$Cierre3 = lag(SP500$Cierre, k=3)
SP500$Cierre4 = lag(SP500$Cierre, k=4)
SP500$Cierre5 = lag(SP500$Cierre, k=5)

我想要的是另一種創建這些列的方法,但在 R 中使用這樣的變量:

i = 11

SP500$(paste("Cierre",i)) = lag(SP500$Cierre, k=i)

任何的想法?

非常感謝您提前。

因為你有一個 xts 對象,只是添加帶有 lapply 的列是行不通的。 滯后函數的返回是另一個 xts 對象。 合並這些數據的最簡單方法是使用合並。

我將給出一個可重現的示例,您可以對其進行調整以滿足您的需要。 lapplylag結合將創建滯后 xts 對象的列表。 我們使用Reducemerge這些合並回主 xts 對象。

# use quantmod to get SPY data
library(quantmod)

SPY <- getSymbols("SPY", auto.assign = FALSE)

i <- 3
# use of Cl function to find the close.
# beware of multiple close columns
lagged_data <- lapply(1:i,function(x) lag(Cl(SPY), x))
# name the lagged data
names(lagged_data) <- paste0("close", 1:i)

# use of reduce and merge to combine everything
SPY <- Reduce(merge, lagged_data, SPY)

head(SPY)

           SPY.Open SPY.High SPY.Low SPY.Close SPY.Volume SPY.Adjusted SPY.Close.1 SPY.Close.2 SPY.Close.3
2007-01-03   142.25   142.86  140.57    141.37   94807600     111.1660          NA          NA          NA
2007-01-04   141.23   142.05  140.61    141.67   69620600     111.4019      141.37          NA          NA
2007-01-05   141.33   141.40  140.38    140.54   76645300     110.5134      141.67      141.37          NA
2007-01-08   140.82   141.41  140.25    141.19   71655000     111.0245      140.54      141.67      141.37
2007-01-09   141.31   141.60  140.40    141.07   75680100     110.9301      141.19      140.54      141.67
2007-01-10   140.58   141.57  140.30    141.54   72428000     111.2997      141.07      141.19      140.54

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM