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

Asked

Viewed 530 times

3

Hello, I would like to know how to calculate the price variation from one period to another. Example:

Year | Price

2007 | 25

2008 | 30

2009 | 7

2010 | 15

... |...|...

The new column would be:

Year | Price | Change

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 that. Thanks in advance !

1 answer

6


You can use the function diff():

#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 function diff() ignores the first element. To get the result of your example, we can use the function append() 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
  • Thanks for the answer ! But I forgot to put a part of the problem. Company | Year | Price | 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 ... |... |...|... There are several companies. This command would solve as well ??

Browser other questions tagged

You are not signed in. Login or sign up in order to post.