2
我在網上找不到解決方案。兩個xts對象在行數和列數上匹配。仍然出現合併操作的以下錯誤 - 「要替換的項目數量不是替換長度的倍數」。合併兩個xts對象時出錯
以下是R代碼以及臨時步驟的打印輸出。我對R有點新,所以如果你發現程序中的任何步驟都可以做得更好,那麼你是否也可以爲我提供建議。謝謝。
> # LOAD THE SPY DATA AND CREATE A DATA FRAME WITH RETURN COLUMN
> library(quantmod)
> library(PerformanceAnalytics)
> getSymbols("SPY", src='yahoo', index.class=c("POSIXt","POSIXct"), from='2002-01-01')
> SPY<-to.monthly(SPY)
> SPY.ret<-Return.calculate(SPY$SPY.Close)
> print(head(SPY.ret))
SPY.Close
Jan 2002 NA
Feb 2002 -0.018098831
Mar 2002 0.029868840
Apr 2002 -0.059915390
May 2002 -0.005951292
Jun 2002 -0.080167070
> index(SPY.ret) = as.Date(index(SPY)) # Convert to Date format as xts index is a Date.
> colnames(SPY.ret) <- "SPY"
> print(head(SPY.ret))
SPY
2002-01-01 NA
2002-02-01 -0.018098831
2002-03-01 0.029868840
2002-04-01 -0.059915390
2002-05-01 -0.005951292
2002-06-01 -0.080167070
> #LOAD THE TRADE FILE & CREATE A DATA FRAME WITH PROFIT COLUMN
> trades = as.xts(read.zoo(file="Anvi/CSV/ARS_EW_R2_SPDR.csv", index.column="Exit.time", format="%m/%d/%Y", header=TRUE, sep=","))
Warning message:
In zoo(rval3, ix) :
some methods for 「zoo」 objects do not work if the index entries in ‘order.by’ are not unique
> df = trades$Profit
> print(head(df))
Profit
2003-09-30 " 0.079734219"
2004-01-31 " 0.116722585"
2004-03-31 " 0.060347888"
2004-04-30 " 0.100379816"
2004-07-31 " 0.084048027"
2004-07-31 " 0.018710103"
> df$Profits = as.numeric(trades$Profit)
> df = df$Profit #Inefficent way to convert Profit column to numeric?
> print(head(df))
Profit
2003-09-30 0.07973422
2004-01-31 0.11672259
2004-03-31 0.06034789
2004-04-30 0.10037982
2004-07-31 0.08404803
2004-07-31 0.01871010
> df = aggregate(df, by=index(df))
> colnames(df) = "Profit"
> print(head(df))
Profit
2003-09-30 0.07973422
2004-01-31 0.11672259
2004-03-31 0.06034789
2004-04-30 0.10037982
2004-07-31 0.10275813
2004-11-30 0.02533904
>
> #MERGE THE SPY RET AND TRADE RESULTS DATA FRAMES
> temp = head(df)
> temp1 = head(SPY.ret)
> print(temp)
Profit
2003-09-30 0.07973422
2004-01-31 0.11672259
2004-03-31 0.06034789
2004-04-30 0.10037982
2004-07-31 0.10275813
2004-11-30 0.02533904
> print(temp1)
SPY
2002-01-01 NA (Note: I tried replacing NA with 0 but still same error).
2002-02-01 -0.018098831
2002-03-01 0.029868840
2002-04-01 -0.059915390
2002-05-01 -0.005951292
2002-06-01 -0.080167070
> mdf = merge(x=temp, y=temp1, all=TRUE)
Error in z[match0(index(a), indexes), ] <- a[match0(indexes, index(a)), :
number of items to replace is not a multiple of replacement length
>
什麼我想上面做的是合併對象,從而導致物體的指數是工會,有兩列「SPY」,「利潤」。合併對象中每列中的空單元格都填充爲0.
謝謝。這解決了這個問題。此致謝 – Atrad
顯示填充= 0。我不知道。 – Atrad