CK TUNG
CK TUNG

Reputation: 51

xts object multiply by a vector in R

I have this sample in R

    require("quantmod") ;
    getSymbols(c("AUD=X","GBP=X","JPY=X")) ;
    ccyportfolio <- merge(`AUD=X`[,4], `GBP=X`[,4], `JPY=X`[,4]) * c(50e+6, 50e+6, -80e+6) ;

But the results are

                  AUD.X.Close GBP.X.Close JPY.X.Close 
    2007-01-01    63000000   -40800000  5944000000
    2007-01-02    63000000    25500000 -9506400000
    2007-01-03  -100800000    25500000  5967000000
    2007-01-04    64000000   -40800000  5941500000
    2007-01-05    64000000    26000000 -9495200000
    2007-01-08  -102400000    26000000  5934500000

But I would expect the correct result to be this but don't understand why xts cannot multiply by a vector directly.

                AUD.X.Close GBP.X.Close JPY.X.Close
    2007-01-01    63000000    25500000 -9510400000
    2007-01-02    63000000    25500000 -9506400000
    2007-01-03    63000000    25500000 -9547200000
    2007-01-04    64000000    25500000 -9506400000 
    2007-01-05    64000000    26000000 -9495200000
    2007-01-08    64000000    26000000 -9495200000

Upvotes: 2

Views: 1020

Answers (1)

tonytonov
tonytonov

Reputation: 25608

This is somewhat linked to this question. What you get is a result of recycling rule; the simplest override of this behaviour is probably

df <- merge(`AUD=X`[,4], `GBP=X`[,4], `JPY=X`[,4])
v <- c(50e+6, 50e+6, -80e+6)
as.xts(t(t(df) * v)))

           AUD.X.Close GBP.X.Close JPY.X.Close
2007-01-01     6.3e+07    25500000 -9510400000
2007-01-02     6.3e+07    25500000 -9506400000
2007-01-03     6.3e+07    25500000 -9547200000
2007-01-04     6.4e+07    25500000 -9506400000
2007-01-05     6.4e+07    26000000 -9495200000
2007-01-08     6.4e+07    26000000 -9495200000

Though I believe there exists a more readable solution.

Upvotes: 1

Related Questions