R - How to calculate the price change from one period to the other?

3

Hello, I'd like to know how to calculate the price change from one period to the next. Example:

  

Year | Price

     

2007 | 25

     

2008 | 30

     

2009 | 7

     

2010 | 15

... | ... | ...

The new column would look like:

  

Year | Contact Us | Variation

     

2007 | 25 | 25-0 = 25

     

2008 | 30 | 30-25 = 5

     

2009 | 7 | 7-30 = -23

     

2010 | 15 | 15-7 = 8

     

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

I have no idea how to do this. Thank you in advance!

    
asked by anonymous 03.04.2018 / 01:08

1 answer

5

You can use the diff() function:

#dados
df <- data.frame(Ano = c(2007,2008,2009,2010), Preço = c(25,30,7,15))

diff(df$Preço)
# [1]   5 -23   8

The diff() function ignores the first element. To get the result of your example, we can use the append() function to add the first element:

df$Variação <- append(df$Preço[1], diff(df$Preço))

df
#    Ano Preço Variação
# 1 2007    25       25
# 2 2008    30        5
# 3 2009     7      -23
# 4 2010    15        8
    
03.04.2018 / 01:44