library(magrittr)
library(ggplot2)

conn <- fd::get_db_connection()
fd::use_db(conn, "sykdomspuls")

d <- dplyr::tbl(conn, "normomo_standard_results") %>%
  dplyr::filter(YoDi>=2009) %>%
  dplyr::filter(age=="Total") %>%
  dplyr::collect() %>%
  fd::latin1_to_utf8()
d
d[, normal_lower := Pnb - abs(UPIb2 - Pnb)]
d[normal_lower < 0, normal_lower := 0]
d[, normal_upper:=UPIb2]
d[, threshold_high := normal_upper*1.2]

d[, status:="normal"]
d[nbc>normal_upper, status:="medium"]
d[nbc>threshold_high, status:="high"]

xtabs(~d$status)

d[,excess_threshold  := nbc- normal_upper]

d[,is_alert_norway := nbc> normal_upper&location_code=="norway"]
d[,is_alert_norway := as.logical(max(is_alert_norway, na.rm=T)), by=wk]
d[,is_alert_medium := nbc> normal_upper & nbc<threshold_high]
d[,is_alert_high := nbc> threshold_high]

x <- d[,.(
  num_alerts_medium=sum(is_alert_medium, na.rm=T),
  num_alerts_high=sum(is_alert_high, na.rm=T)
), keyby=.( 
  wk,
  is_alert_norway
  )]

x

x[,.(
  num_alerts_medium=mean(num_alerts_medium, na.rm=T),
  num_alerts_high=mean(num_alerts_high, na.rm=T)
), keyby=.( 
  is_alert_norway
  )]

x[,.(
  perc_alerts_norway=mean(is_alert_norway, na.rm=T)
), keyby=.( 
  num_alerts_medium
  )]

x[,.(
  perc_alerts_norway=mean(is_alert_norway, na.rm=T)
), keyby=.( 
  num_alerts_high
  )]

p <- d[,.(
  excess_from_threshold=round(mean(excess_threshold, na.rm=T)),
  threshold=round(mean(normal_upper, na.rm=T)),
  baseline=round(mean(Pnb, na.rm=T))
), keyby=.( 
  status,
  location_code
  )]
p[status=="high",status := "[Over 1.2x higher than normal"]
p[status=="medium",status := "[1.0-1.2x higher than normal"]

xlsx::write.xlsx(
  p,
  fs::path(
    fd::path("results","thresholds.xlsx")
  ),
  row.names=F
)

d[, status_z:="normal"]
d[nbc>UPIb2, status_z:="medium"]
d[nbc>UPIb4, status_z:="high"]

xtabs(~status+status_z,data= d[location_code=="norway"])

d[status=="medium" & location_code=="norway"]

q <- ggplot(d, aes(x=wk))
q <- q + geom_ribbon(aes(ymin = normal_lower, ymax = normal_upper, fill = "4expected"), alpha = 0.7)
q <- q + geom_ribbon(aes(ymin = normal_upper, ymax = threshold_high, fill = "3high"), alpha = 0.7)
q <- q + geom_ribbon(aes(ymin = threshold_high, ymax = Inf, fill = "2veryhigh"), alpha = 0.7)
q <- q + geom_point(data=d[status!="normal"],mapping=aes(y=nbc))
q <- q + facet_wrap(~location_code,ncol=2,scales="free")
q <- q + fhiplot::theme_fhi_basic()
q


folkehelseinstituttet/dashboards_normomo documentation built on March 20, 2020, 4:16 p.m.