1

我有这样填充的数据集:

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 命名的列?

4

1 回答 1

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]东西。

于 2012-07-08T18:24:25.507 回答