library(data.table)
library(magrittr)
# 讀資料
tao_b <-
  fread(
    "
    Area Project Type Date       Price
    A    x       J    2012/6/18  1.1
    A    x       J    2012/7/2   2.1
    A    x       J    2012/7/6   3.2
    A    x       J    2012/7/9   2.5
    A    y       K    2012/7/15  10
    A    y       K    2012/7/18  20
    B    z       L    2012/7/20  111
    B    z       L    2012/7/23  221
    B    z       L    2012/7/23  222
    B    z       L    2012/7/24  110"
  )

# 一些必要清理
tao_b %>%
  .[, Date := as.POSIXct(Date)] %>%
  .[, Price := as.double(Price)] %>%
  .[, Price.med := median(Price), by = Area:Date] %>%
  setorder(., Area, Project, Type, Date)

res <-
  tao_b %>%
  cbind(.,
        Date.previous = tao_b[, c(Date[1], Date[1:(.N - 1)]), by = Area:Type]$V1,
        Price.med.previous = tao_b[, c(NA, Price.med[1:(.N - 1)]), by = Area:Type]$V1) %>%
  .[, c("delta.Price.med", "delta.Date") :=
      list(ifelse(is.na(Price.med.previous), 0, Price.med - Price.med.previous),
           ifelse(is.na(Date.previous), 0, (Date - Date.previous) / 60 / 60 / 24))]

tao_b
res
