2

First of all, I have a dataframe (lets call it "years") with 5 rows and 10 columns. I need to build a new one doing (x1-x2)/x1, being x1 the first element and x2 the second element of a column in "years", then (x2-x3)/x2 and so forth. I thought rollapply would be the best tool for the task, but I can't figure out how to define such function to insert it in rollapply.

I'm new to R, so I hope my question is not too basic. Anyway, I couldn't find a similar question here so I'd be really thankful if someone could help me.

Stedy
  • 7,359
  • 14
  • 57
  • 77
user6894
  • 21
  • 1
  • 2
    Take a look at `diff` function and try to make your question/problem [reproducble](http://stackoverflow.com/q/5963269/1315767) – Jilber Urbina Jun 02 '14 at 20:16

2 Answers2

1

You can use transform, diff and length, no need to use rollapply

> df <- head(iris,5)  # some data
> transform(df, New = c(NA, diff(Sepal.Length)/Sepal.Length[-length(Sepal.Length)] ))
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species         New
1          5.1         3.5          1.4         0.2  setosa          NA
2          4.9         3.0          1.4         0.2  setosa -0.03921569
3          4.7         3.2          1.3         0.2  setosa -0.04081633
4          4.6         3.1          1.5         0.2  setosa -0.02127660
5          5.0         3.6          1.4         0.2  setosa  0.08695652
Jilber Urbina
  • 58,147
  • 10
  • 114
  • 138
0

diff.zoo in the zoo package with the arithmetic=FALSE argument will divide each number by the prior in each column:

library(zoo)
as.data.frame(1 - diff(zoo(DF), arithmetic = FALSE))
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341