R - How to calculate price variation for different periods and companies?

3

Hello, I'd like to know how to calculate the price change from one period to the next. Being that are several years for several companies. Example:

  

Company | Year | Price

     

1 | 2007 | 25

     

1 | 2008 | 30

     

1 | 2009 | 7

     

1 | 2010 | 15

     

2 | 2007 | 20

     

2 | 2008 | 27

     

2 | 2009 | 7

     

2 | 2010 | 20

... | ... | ... | ...

The new column would look like:

  

Company | Year | Contact Us | Variation

     

1 | 2007 | 25 | 25-0 = 25

     

1 | 2008 | 30 | 30-25 = 5

     

1 | 2009 | 7 | 7-30 = -23

     

1 | 2010 | 15 | 15-7 = 8

     

2 | 2007 | 20 | 20-0 = 20

     

2 | 2008 | 27 | 27-20 = 7

     

2 | 2009 | 7 | 7-27 = -20

     

2 | 2010 | 20 | 20-7 = 13

     

... | ... | ... | ...

I have no idea how to do this.

would you use diff?

Thank you in advance!

    
asked by anonymous 04.04.2018 / 00:01

1 answer

7

The ave function has been done to solve this type of problem.

dados$Variação <- ave(dados$Preço, dados$Empresa, FUN = function(x) c(x[1], diff(x)))

DATA.

dados <-
structure(list(Empresa = c(1, 1, 1, 1, 2, 2, 2, 2), Ano = c(2007, 
2008, 2009, 2010, 2007, 2008, 2009, 2010), Preço = c(25L, 30L, 
7L, 15L, 20L, 27L, 7L, 20L)), .Names = c("Empresa", "Ano", "Preço"
), class = "data.frame", row.names = c(NA, -8L))
    
04.04.2018 / 00:09