我的数据集填充方式如下:
tickers <- c("SPY","DIA")
l_ply(tickers, function(sym) try(getSymbols(sym, from="2012-03-01",
to=Sys.Date())))
ClosePrices <- do.call(merge, lapply(tickers, function(x) Cl(get(x))))
tail(ClosePrices)
SPY.Close DIA.Close
2012-06-29 136.10 128.45
2012-07-02 136.51 128.36
和
rsipx <- do.call(merge, lapply(ClosePrices, FUN=function(ClosePrices) RSI(ClosePrices)))
tail(rsipx)
SPY.Close DIA.Close
2012-06-29 58.36391 58.92043
2012-07-02 59.37153 58.53483
我无法解决的问题是当我应用为每个输入生成多列的函数时。在这种情况下,ADX产生4个值(DIp DIn DX ADX):
adxpx <- do.call(merge, lapply(tickers, FUN=function(tickers) ADX(get(tickers))))
tail(adxpx)
DIp DIn DX ADX DIp.1 DIn.1 DX.1 ADX.1
2012-06-29 53.47713 35.90631 19.65780 15.30299 55.14765 36.05527 20.93395 18.20818
2012-07-02 55.79485 32.58420 26.26262 16.08582 56.67699 33.08770 26.27903 18.78467
如何获取相应的列名而不是数字? (DX.DIA而不是DX.1),或者只选择$ ADX命名列?
答案 0 :(得分:3)
只需将paste
代码名称添加到您传递给lapply
的函数内的列名称中:
foo <- function(tickers){
res <- ADX(get(tickers))
colnames(res) <- paste(colnames(res),tickers,sep = ".")
res
}
adxpx <- do.call(merge, lapply(tickers, FUN=foo))
如果只需要一列,则可以更改函数foo
以仅选择该列。比如说,通过添加一行(在更改列名之前),如res <- res[,4]
或其他东西。