0

How can I make R take an xts object and divide each value of it to a corresponding (by date) value from other, bigger, xts object?

Suppose I have an xts object with sales in currency A in one xts object:

2018-01-01 200.0 

2018-01-04 400.0

And I have currency exchange rate in other xts object:

2018-01-01 5.0

2018-01-02 5.5

2018-01-03 5.7

2018-01-04 6.0

2018-01-05 5.9

I want to divide each of sales values by currency rate at this day and get a resulting xts object like:

2018-01-01 40.0

2018-01-04 66.7
LyzandeR
  • 37,047
  • 12
  • 77
  • 87
Egor_RU
  • 15
  • 4
  • Welcome to StackOverflow! Please read the info about [how to ask a good question](http://stackoverflow.com/help/how-to-ask) and how to give a [reproducible example](http://stackoverflow.com/questions/5963269). This will make it much easier for others to help you. – Sotos Jan 11 '18 at 13:44

1 Answers1

0

You can merge the objects (so that the dates align) and then divide the columns.

library(xts)
sales <- xts(c(200, 400), as.Date(c('2018-01-01','2018-01-04')))
exchange <- xts(c(5, 5.5, 5.7, 6.0, 5.9),
            as.Date(c('2018-01-01','2018-01-02','2018-01-03','2018-01-04','2018-01-05')))

merged <- merge(sales, exchange, all=c(TRUE,FALSE))
converted <- merged$sales / merged$exchange
converted
#           sales
#2018-01-01   200
#2018-01-04   400
jmuhlenkamp
  • 2,102
  • 1
  • 14
  • 37