Home > Back-end >  How adjust order output table
How adjust order output table

Time:11-08

Can tell me why the order is incorrect in my generated table below?. I filtered from 11/07 (Sunday) to 11/13 (Saturday). But as you can see, in the generated table, Saturday is getting by the second and not the last. The rest is OK, only Saturday went wrong.

library(dplyr)

Test <- structure(list(date1 = as.Date(c("2021-11-01","2021-11-01","2021-11-01","2021-11-01","2021-11-01","2021-11-01","2021-11-01")),
                      date2 = as.Date(c("2021-10-18","2021-10-19","2021-10-20","2021-10-21","2021-10-22","2021-10-23","2021-10-24")),
                       Week = c("Monday", "Tuesday", "Wednesday", "Thursday","Friday","Saturday","Sunday"),
                      Category = c("FDE", "FDE", "FDE", "FDE","FDE","FDE","FDE"),
                       time = c(4, 6, 3, 2,3,3,4)), class = "data.frame",row.names = c(NA, -7L))

  wk_port2eng <- data.frame(
    WeekE = c("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"),
    WeekP = c("segunda-feira", "terca-feira", "quarta-feira", "quinta-feira",  "sexta-feira", "sabado", "domingo")
  )

left_join(Test, wk_port2eng, by = c("Week" = "WeekE")) %>%      
  arrange(match(WeekP, weekdays(as.Date(c("2021-11-07", "2021-11-13"))))) %>%
 select(-WeekP)
       date1      date2      Week Category time
1 2021-11-01 2021-10-24    Sunday      FDE    4
2 2021-11-01 2021-10-23  Saturday      FDE    3
3 2021-11-01 2021-10-18    Monday      FDE    4
4 2021-11-01 2021-10-19   Tuesday      FDE    6
5 2021-11-01 2021-10-20 Wednesday      FDE    3
6 2021-11-01 2021-10-21  Thursday      FDE    2
7 2021-11-01 2021-10-22    Friday      FDE    3

CodePudding user response:

You can sort by the weekday using lubridate::wday

left_join(Test, wk_port2eng, by = c("Week" = "WeekE")) %>%    
 arrange(match(WeekP, weekdays(as.Date(c("2021-11-07", "2021-11-13"))))) %>%
 arrange(lubridate::wday(date2)) %>%
 select(-WeekP)
#>        date1      date2      Week Category time
#> 1 2021-11-01 2021-10-24    Sunday      FDE    4
#> 2 2021-11-01 2021-10-18    Monday      FDE    4
#> 3 2021-11-01 2021-10-19   Tuesday      FDE    6
#> 4 2021-11-01 2021-10-20 Wednesday      FDE    3
#> 5 2021-11-01 2021-10-21  Thursday      FDE    2
#> 6 2021-11-01 2021-10-22    Friday      FDE    3
#> 7 2021-11-01 2021-10-23  Saturday      FDE    3

Created on 2021-11-07 by the reprex package (v2.0.0)

  •  Tags:  
  • r
  • Related