0

I have a table and I would like to add a column that calculates the percentage compared to the previous line. You have to do as calculation takes the line 1 divided by line 2 and on the line 2, you indicate the result

Example

month <- c(10,11,12,13,14,15)
sell <-c(258356,278958,287928,312254,316287,318999)
df <- data.frame(month, sell)

df %>% mutate(augmentation = sell[month]/sell[month+1])
  month   sell  resultat
1    10 258356        NA
2    11 278958 0.9261466
3    12 287928 0.9688464
4    13 312254 0.9220955
5    14 316287 0.9872489
6    15 318999 0.9914984
user438383
  • 5,716
  • 8
  • 28
  • 43

1 Answers1

0

dplyr

You can just use lag like this:

library(dplyr)
df %>%
  mutate(resultat = lag(sell)/sell)

Output:

  month   sell  resultat
1    10 258356        NA
2    11 278958 0.9261466
3    12 287928 0.9688464
4    13 312254 0.9220955
5    14 316287 0.9872489
6    15 318999 0.9914984

data.table

Another option is using shift:

library(data.table)
setDT(df)[, resultat:= shift(sell)/sell][]

Output:

   month   sell  resultat
1:    10 258356        NA
2:    11 278958 0.9261466
3:    12 287928 0.9688464
4:    13 312254 0.9220955
5:    14 316287 0.9872489
6:    15 318999 0.9914984
Quinten
  • 35,235
  • 5
  • 20
  • 53