fork download
  1. library(data.table)
  2. library(magrittr)
  3. # 讀資料
  4. tao_b <-
  5. "
  6. Area Project Type Date Price
  7. A x J 2012/6/18 1.1
  8. A x J 2012/7/2 2.1
  9. A x J 2012/7/6 3.2
  10. A x J 2012/7/9 2.5
  11. A y K 2012/7/15 10
  12. A y K 2012/7/18 20
  13. B z L 2012/7/20 111
  14. B z L 2012/7/23 221
  15. B z L 2012/7/23 222
  16. B z L 2012/7/24 110"
  17. )
  18.  
  19. # 一些必要清理
  20. tao_b %>%
  21. .[, Date := as.POSIXct(Date)] %>%
  22. .[, Price := as.double(Price)] %>%
  23. .[, Price.med := median(Price), by = Area:Date] %>%
  24. setorder(., Area, Project, Type, Date)
  25.  
  26. res <-
  27. tao_b %>%
  28. cbind(.,
  29. Date.previous = tao_b[, c(Date[1], Date[1:(.N - 1)]), by = Area:Type]$V1,
  30. Price.med.previous = tao_b[, c(NA, Price.med[1:(.N - 1)]), by = Area:Type]$V1) %>%
  31. .[, c("delta.Price.med", "delta.Date") :=
  32. list(ifelse(is.na(Price.med.previous), 0, Price.med - Price.med.previous),
  33. ifelse(is.na(Date.previous), 0, (Date - Date.previous) / 60 / 60 / 24))]
  34.  
  35. tao_b
  36. res
  37.  
Success #stdin #stdout 0.29s 190080KB
stdin
Standard input is empty
stdout
    Area Project Type       Date Price Price.med
 1:    A       x    J 2012-06-18   1.1       1.1
 2:    A       x    J 2012-07-02   2.1       2.1
 3:    A       x    J 2012-07-06   3.2       3.2
 4:    A       x    J 2012-07-09   2.5       2.5
 5:    A       y    K 2012-07-15  10.0      10.0
 6:    A       y    K 2012-07-18  20.0      20.0
 7:    B       z    L 2012-07-20 111.0     111.0
 8:    B       z    L 2012-07-23 221.0     221.5
 9:    B       z    L 2012-07-23 222.0     221.5
10:    B       z    L 2012-07-24 110.0     110.0
    Area Project Type       Date Price Price.med Date.previous
 1:    A       x    J 2012-06-18   1.1       1.1    2012-06-18
 2:    A       x    J 2012-07-02   2.1       2.1    2012-06-18
 3:    A       x    J 2012-07-06   3.2       3.2    2012-07-02
 4:    A       x    J 2012-07-09   2.5       2.5    2012-07-06
 5:    A       y    K 2012-07-15  10.0      10.0    2012-07-15
 6:    A       y    K 2012-07-18  20.0      20.0    2012-07-15
 7:    B       z    L 2012-07-20 111.0     111.0    2012-07-20
 8:    B       z    L 2012-07-23 221.0     221.5    2012-07-20
 9:    B       z    L 2012-07-23 222.0     221.5    2012-07-23
10:    B       z    L 2012-07-24 110.0     110.0    2012-07-23
    Price.med.previous delta.Price.med delta.Date
 1:                 NA             0.0          0
 2:                1.1             1.0         14
 3:                2.1             1.1          4
 4:                3.2            -0.7          3
 5:                 NA             0.0          0
 6:               10.0            10.0          3
 7:                 NA             0.0          0
 8:              111.0           110.5          3
 9:              221.5             0.0          0
10:              221.5          -111.5          1