alex M.
alex M.

Reputation: 11

Column names after lapply

I have dataset filled like this:

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

and

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

The problem I can't solve is when I apply a function which generates multiple columns for each input. In this case ADX produces 4 values (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

How can I get the corresponding column names instead of a number? (DX.DIA instead of DX.1) , or select only the $ADX named columns ?

Upvotes: 1

Views: 917

Answers (1)

joran
joran

Reputation: 173557

Just paste the ticker name onto the column names inside the function you pass to lapply:

foo <- function(tickers){
    res <-  ADX(get(tickers))
    colnames(res) <- paste(colnames(res),tickers,sep = ".")
    res
}
adxpx <- do.call(merge, lapply(tickers, FUN=foo))  

If you want only one column, you can change the function foo to select only that column. Say, by adding a line (before altering the column names) like res <- res[,4] or something.

Upvotes: 3

Related Questions