Home > Back-end >  How to calculate % difference between 2 rows in R?
How to calculate % difference between 2 rows in R?

Time:07-10

As the question says: what is the best way to calculate the % difference between weeks.

I'm putting an image to see what is the expetec result (in form, numbers are different):

enter image description here

data has 3 weeks... but it could be more. The idea is always compare WeekN with WeekN - 1, WeekN - 1 vs WeekN - 2, and so on

df:

df <- structure(list(week = c(25, 26, 27), viernes = c(6027, 4731, 
6022), sábado = c(NA, 7807, 5059), domingo = c(NA, 10360, 5914
), lunes = c(NA, 6165, 6443), martes = c(NA, 5274, 7157), miércoles = c(NA, 
4764, 7411), jueves = c(NA, 4377, 7176)), class = c("tbl_df", 
"tbl", "data.frame"), row.names = c(NA, -3L))

CodePudding user response:

Try this

df$week <- as.character(df$week)
for(i in 1:(nrow(df)-1)){
    df[nrow(df) 1 ,] <-c(paste0("var % week " ,df$week[i 1] , " vs ", df$week[i]),
    round((df[-1][i 1 ,] - df[-1][i,])/df[-1][i,]*100))
}
  • Output
# A tibble: 5 × 8
  week                viernes sábado domingo lunes martes miércoles jueves
  <chr>                 <dbl>  <dbl>   <dbl> <dbl>  <dbl>     <dbl>  <dbl>
1 25                     6027     NA      NA    NA     NA        NA     NA
2 26                     4731   7807   10360  6165   5274      4764   4377
3 27                     6022   5059    5914  6443   7157      7411   7176
4 var % week 26 vs 25     -22     NA      NA    NA     NA        NA     NA
5 var % week 27 vs 26      27    -35     -43     5     36        56     64

CodePudding user response:

require(data.table)
dt1 <- data.table(df)
dt1.long <- melt(dt1, id.vars = 'week', variable.name='DayOfWeek')
dt1.long[,      prev.week:=shift(week, type='lag'),by=DayOfWeek]  
dt1.long[,value.prev.week:=shift(value,type='lag'),by=DayOfWeek]  
dt1.long[!is.na(prev.week), label.change:=paste0('var % w', week, ' vs w',prev.week)]
dt1.long[!is.na(value) & !is.na(value.prev.week), change:=scales::label_percent()((value-value.prev.week)/value.prev.week)]

dt2 <- dcast(dt1.long, week label.change~DayOfWeek, value.var = 'change')
  •  Tags:  
  • r
  • Related