-2

I have to calculate the Monthly Return for some businesses using this function:

monthly return for month i+1 = (closing price in month i+1 - closing price in month i)/closing price in month i

I have a data set that contains the closing price every month for about 10 year. How would I create/use a function to calculate the MR for each month?

  • 2
    [How to make a great R reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – zero323 Oct 27 '13 at 23:08

1 Answers1

0
monthly <- c(100, 120, 130, 100, 140)  # replace this of course with actual data

result <- rep(NA, length(monthly))
for (i in 1:(length(monthly)-1)) {
   result[i+1] <- (monthly[i+1] - monthly[i]) / monthly[i] 
}

result will now contain your answer. Note that the first position will contain an NA, since you are not interested in month i being 1.

PascalVKooten
  • 20,643
  • 17
  • 103
  • 160
  • ahhh okay thanks that makes a lot of sense. I was trying to do something like that but tried to make it 1:length(monthly). Thanks! – Andrew Austin Oct 27 '13 at 23:17