Advertisement
ffee21

Untitled

Jul 4th, 2016
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 1.63 KB | None | 0 0
  1. rm(list=ls())
  2.  
  3. library(RMySQL)
  4. library(dplyr)
  5. library(ggplot2)
  6.  
  7. con = dbConnect(MySQL(),user="root", password="qwer1234",
  8.                 dbname="nhiss", host="localhost")
  9. myQuery <- "SELECT
  10.              CONCAT(MDCARE_STRT_YEAR, '-', LPAD(MDCARE_STRT_MONTH, 2, '0')) AS YEARMONTH,
  11.              MDCARE_STRT_YEAR,
  12.              MDCARE_STRT_MONTH,
  13.              MDCARE_STRT_DAY,
  14.              MDCARE_STRT_DT,
  15.              THE_ID
  16.            FROM MCARE
  17.            ORDER BY MDCARE_STRT_DT ASC"
  18. R1 <- dbGetQuery(con, myQuery)
  19. R2 <- tbl_df(R1)
  20. R3 <- R2 %>%
  21.   group_by(YEARMONTH, MDCARE_STRT_YEAR, MDCARE_STRT_MONTH) %>%
  22.   summarize(count = n_distinct(THE_ID)) %>%
  23.   arrange(MDCARE_STRT_YEAR, MDCARE_STRT_MONTH)
  24.  
  25.  
  26. R3$YEARMONTH = as.factor(R3$YEARMONTH)
  27. R3$MDCARE_STRT_YEAR = as.factor(R3$MDCARE_STRT_YEAR)
  28. R3$MDCARE_STRT_MONTH = as.factor(R3$MDCARE_STRT_MONTH)
  29. R3$count = as.numeric(R3$count)
  30.  
  31. ggplot(R3, aes(x=YEARMONTH, y=count)) +
  32.   geom_bar(stat="identity") +
  33.   theme(axis.text.x = element_text(angle=90, vjust=0.5, hjust=1))
  34.  
  35. ggplot(R3, aes(MDCARE_STRT_MONTH, count)) +
  36.   geom_bar(aes(fill=MDCARE_STRT_YEAR), stat="identity", position="dodge") +
  37.   theme(axis.text.x = element_text(angle=90, vjust=0.5, hjust=1))
  38.  
  39. R4 <- R3 %>%
  40.   group_by(MDCARE_STRT_MONTH) %>%
  41.   summarize(avg = mean(count), stdv = sd(count)) %>%
  42.   select(MDCARE_STRT_MONTH, avg, stdv) %>%
  43.   arrange(MDCARE_STRT_MONTH)
  44.  
  45. ggplot(R4, aes(x=MDCARE_STRT_MONTH, y=avg)) +
  46.   geom_bar(stat="identity") +
  47.   coord_cartesian(xlim=c(1, 12)) +
  48.   geom_errorbar(data=R4, mapping=aes(x=MDCARE_STRT_MONTH, ymin=avg-stdv, ymax=avg+stdv))
  49.  
  50. dbDisconnect(con)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement