-
Notifications
You must be signed in to change notification settings - Fork 0
/
Corona_Prediction.Rmd
850 lines (654 loc) · 36.9 KB
/
Corona_Prediction.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
---
title: "Corona_Analysis"
author: "Steven Smith, PhD"
date: "3/18/2020"
output:
html_document:
toc: yes
pdf_document:
toc: yes
---
# The 2019-2020 Coronavirus Pandemic Analysis
Contact: [Smith Research](https://stevenbsmith.net)
## BACKGROUND & APPROACH
I wanted to track and trend the coronavirus outbreak on my own curiosity. There are some interesting questions that may fall out of this, as it is a very historic moment, including scientifically and analytically (we have a large amount of data being shared across the globe, analyzed in real-time). The world has come to a halt because of it.
This analysis attempts to answer the following questions (more to come):
1. What does the trend of the pandemic look like to date?
2. What are future case predictions based on historical model?
3. What interesting quirks or patterns emerge?
ASSUMPTIONS & LIMITATIONS:
* This data is limited by the source. I realized early on that depending on source there were conflicting # of cases. Originally I was using JHU data... but this was always 'ahead' of the Our World In Data. I noticed that JHU's website was buggy- you clicked on the U.S. stats but it didn't reflect the U.S.. So I changed data sources to be more consistent with what is presented in the media (and Our World In Data has more extensive plots I can compare my own to). An interesting aside might be why the discrepancy? Was I missing something?
* Defintiions are important as is the idea that multiple varibales accumulate in things like total cases (more testing for example).
SOURCE RAW DATA:
* https://ourworldindata.org/coronavirus
* https://github.com/CSSEGISandData/COVID-19/
* <mobility>
INPUT DATA LOCATION: github (https://github.com/sbs87/coronavirus/tree/master/data)
OUTPUT DATA LOCATIOn: github (https://github.com/sbs87/coronavirus/tree/master/results)
## TIMESTAMP
Start: `r paste(timestamp())`
## PRE-ANALYSIS
The following sections are outside the scope of the 'analysis' but are still needed to prepare everything
### UPSTREAM PROCESSING/ANALYSIS
1. Google Mobility Scraping, script available at [get_google_mobility.py](https://github.com/sbs87/coronavirus/blob/master/get_google_mobility.py)
```{bash process_remote_server, eval=F,tidy=T}
# Mobility data has to be extracted from Google PDF reports using a web scraping script (python , written by Peter Simone, https://github.com/petersim1/MIT_COVID19)
# See get_google_mobility.py for local script
python3 get_google_mobility.py
# writes csv file of mobility data as "mobility.csv"
# TODO: customize get_google_mobility.py script, add arguments
```
### SET UP ENVIORNMENT
Load libraries and set global variables
```{r setup, eval=T,collapse=T,tidy=T}
#timestamp start
timestamp()
# clear previous enviornment
rm(list = ls())
##------------------------------------------
## LIBRARIES
##------------------------------------------
library(plyr)
library(tidyverse)
library(ggplot2)
library(reshape2)
library(plot.utils)
library(utils)
library(knitr)
##------------------------------------------
##------------------------------------------
# GLOBAL VARIABLES
##------------------------------------------
user_name<-Sys.info()["user"]
working_dir<-paste0("/Users/",user_name,"/Projects/coronavirus/") # don't forget trailing /
results_dir<-paste0(working_dir,"results/") # assumes diretory exists
results_dir_custom<-paste0(results_dir,"custom/") # assumes diretory exists
Corona_Cases.source_url<-"https://github.com/CSSEGISandData/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv"
Corona_Cases.US.source_url<-"https://github.com/CSSEGISandData/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_US.csv"
Corona_Deaths.US.source_url<-"https://github.com/CSSEGISandData/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_US.csv"
Corona_Deaths.source_url<-"https://github.com/CSSEGISandData/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_global.csv"
Corona_Cases.fn<-paste0(working_dir,"data/",basename(Corona_Cases.source_url))
Corona_Cases.US.fn<-paste0(working_dir,"data/",basename(Corona_Cases.US.source_url))
Corona_Deaths.fn<-paste0(working_dir,"data/",basename(Corona_Deaths.source_url))
Corona_Deaths.US.fn<-paste0(working_dir,"data/",basename(Corona_Deaths.US.source_url))
default_theme<-theme_bw()+theme(text = element_text(size = 14)) # fix this
##------------------------------------------
```
### FUNCTIONS
List of functions
function_name | description
------------- | -----------
prediction_model | outputs case estumate for given log-linear moder parameters slope and intercept
make_long | converts input data to long format (specialized cases)
name_overlaps | outputs the column names intersection and set diffs of two data frame
```{r functions, eval=T}
##------------------------------------------
## FUNCTION: prediction_model
##------------------------------------------
## --- //// ----
# Takes days vs log10 (case) linear model parameters and a set of days since 100 cases and outputs a dataframe with total number of predicted cases for those days
## --- //// ----
prediction_model<-function(m=1,b=0,days=1){
total_cases.log<-m*days+b
total_cases<-10^total_cases.log
prediction<-data.frame(Days_since_100=days,Total_confirmed_cases=total_cases,Total_confirmed_cases.log=total_cases.log)
return(prediction)
}
##------------------------------------------
##------------------------------------------
## FUNCTION: make_long
##------------------------------------------
## --- //// ----
# Takes wide-format case data and converts into long format, using date and total cases as variable/values. Also enforces standardization/assumes data struture naming by using fixed variable name, value name, id.vars,
## --- //// ----
make_long<-function(data_in,variable.name = "Date",
value.name = "Total_confirmed_cases",
id.vars=c("case_type","Province.State","Country.Region","Lat","Long","City","Population")){
long_data<-melt(data_in,
id.vars = id.vars,
variable.name=variable.name,
value.name=value.name)
return(long_data)
}
##------------------------------------------
## THIS WILL BE IN UTILS AT SOME POINT
name_overlaps<-function(df1,df2){
i<-intersect(names(df1),
names(df2))
sd1<-setdiff(names(df1),
names(df2))
sd2<-setdiff(names(df2),names(df1))
cat("intersection:\n",paste(i,"\n"))
cat("in df1 but not df2:\n",paste(sd1,"\n"))
cat("in df2 but not df1:\n",paste(sd2,"\n"))
return(list("int"=i,"sd_1_2"=sd1,"sd_2_1"=sd2))
}
```
### READ IN DATA
* total number of cases. current source: https://github.com/CSSEGISandData (precvious source https://ourworldindata.org/coronavirus)
```{r read_in_data, eval=T,tidy=T}
# Q: do we want to archive previous versions? Maybe an auto git mv?
##------------------------------------------
## Download and read in latest data from github
##------------------------------------------
download.file(Corona_Cases.source_url,destfile = Corona_Cases.fn)
Corona_Totals.raw<-read.csv(Corona_Cases.fn,header = T,stringsAsFactors = F)
download.file(Corona_Cases.US.source_url,destfile = Corona_Cases.US.fn)
Corona_Totals.US.raw<-read.csv(Corona_Cases.US.fn,header = T,stringsAsFactors = F)
download.file(Corona_Deaths.source_url,destfile = Corona_Deaths.fn)
Corona_Deaths.raw<-read.csv(Corona_Deaths.fn,header = T,stringsAsFactors = F)
download.file(Corona_Deaths.US.source_url,destfile = Corona_Deaths.US.fn)
Corona_Deaths.US.raw<-read.csv(Corona_Deaths.US.fn,header = T,stringsAsFactors = F)
#latest date on all data:
paste("US deaths:",names(Corona_Deaths.US.raw)[ncol(Corona_Deaths.US.raw)])
paste("US total:",names(Corona_Totals.US.raw)[ncol(Corona_Totals.US.raw)])
paste("World deaths:",names(Corona_Deaths.raw)[ncol(Corona_Deaths.raw)])
paste("World total:",names(Corona_Totals.raw)[ncol(Corona_Totals.raw)])
```
### PROCESS DATA
* Convert to long format
* Fix date formatting/convert to numeric date
* Log10 transform total # cases
```{r process, eval=T}
##------------------------------------------
## Combine death and total data frames
##------------------------------------------
Corona_Totals.raw$case_type<-"total"
Corona_Totals.US.raw$case_type<-"total"
Corona_Deaths.raw$case_type<-"death"
Corona_Deaths.US.raw$case_type<-"death"
# for some reason, Population listed in US death file but not for other data... Weird. When combining, all datasets will have this column, but US deaths is the only useful one.
Corona_Totals.US.raw$Population<-"NA"
Corona_Totals.raw$Population<-"NA"
Corona_Deaths.raw$Population<-"NA"
Corona_Cases.raw<-rbind(Corona_Totals.raw,Corona_Deaths.raw)
Corona_Cases.US.raw<-rbind(Corona_Totals.US.raw,Corona_Deaths.US.raw)
#TODO: custom utils- setdiff, intersect names... option to output in merging too
##------------------------------------------
# prepare raw datasets for eventual combining
##------------------------------------------
Corona_Cases.raw$City<-"NA" # US-level data has Cities
Corona_Cases.US.raw$Country_Region<-"US_state" # To differentiate from World-level stats
Corona_Cases.US.raw<-plyr::rename(Corona_Cases.US.raw,c("Province_State"="Province.State",
"Country_Region"="Country.Region",
"Long_"="Long",
"Admin2"="City"))
##------------------------------------------
## Convert to long format
##------------------------------------------
#JHU has a gross file format. It's in wide format with each column is the date in MM/DD/YY. So read this in as raw data but trasnform it to be better suited for analysis
# Furthermore, the World and US level data is formatted differently, containing different columns, etc. Recitfy this and combine the world-level stats with U.S. level stats.
Corona_Cases.long<-rbind(make_long(select(Corona_Cases.US.raw,-c(UID,iso2,iso3,code3,FIPS,Combined_Key))),
make_long(Corona_Cases.raw))
##------------------------------------------
## Fix date formatting, convert to numeric date
##------------------------------------------
Corona_Cases.long$Date<-gsub(Corona_Cases.long$Date,pattern = "^X",replacement = "0") # leading 0 read in as X
Corona_Cases.long$Date<-gsub(Corona_Cases.long$Date,pattern = "20$",replacement = "2020") # ends in .20 and not 2020
Corona_Cases.long$Date<-as.Date(Corona_Cases.long$Date,format = "%m.%d.%y")
Corona_Cases.long$Date.numeric<-as.numeric(Corona_Cases.long$Date)
kable(table(select(Corona_Cases.long,c("Country.Region","case_type"))),caption = "Number of death and total case longitudinal datapoints per geographical region")
# Decouple population and lat/long data, refactor to make it more tidy
metadata_columns<-c("Lat","Long","Population")
metadata<-unique(select(filter(Corona_Cases.long,case_type=="death"),c("Country.Region","Province.State","City",all_of(metadata_columns))))
Corona_Cases.long<-select(Corona_Cases.long,-all_of(metadata_columns))
# Some counties are not summarized on the country level. collapse all but US
Corona_Cases.long<-rbind.fill(ddply(filter(Corona_Cases.long,!Country.Region=="US_state"),c("case_type","Country.Region","Date","Date.numeric"),summarise,Total_confirmed_cases=sum(Total_confirmed_cases)),filter(Corona_Cases.long,Country.Region=="US_state"))
# Put total case and deaths side-by-side (wide)
Corona_Cases<-spread(Corona_Cases.long,key = case_type,value = Total_confirmed_cases)
#Compute moratlity rate
Corona_Cases$mortality_rate<-Corona_Cases$death/Corona_Cases$total
#TMP
Corona_Cases<-plyr::rename(Corona_Cases,c("total"="Total_confirmed_cases","death"="Total_confirmed_deaths"))
##------------------------------------------
## log10 transform total # cases
##------------------------------------------
Corona_Cases$Total_confirmed_cases.log<-log(Corona_Cases$Total_confirmed_cases,10)
Corona_Cases$Total_confirmed_deaths.log<-log(Corona_Cases$Total_confirmed_deaths,10)
##------------------------------------------
##------------------------------------------
## Compute # of days since 100th for US data
##------------------------------------------
# Find day that 100th case was found for Country/Province. NOTE: Non US countries may have weird provinces. For example, Frane is summairzed at the country level but also had 3 providences. I've only ensured the U.S. case100 works... so the case100_date for U.S. is summarized both for the entire country (regardless of state) and on a per-state level.
# TODO: consider city-level summary as well. This data may be sparse
Corona_Cases<-merge(Corona_Cases,ddply(filter(Corona_Cases,Total_confirmed_cases>100),c("Country.Region"),summarise,case100_date=min(Date.numeric)))
Corona_Cases$Days_since_100<-Corona_Cases$Date.numeric-Corona_Cases$case100_date
##------------------------------------------
## Add population and lat/long data (CURRENTLY US ONLY)
##------------------------------------------
# TODO Add population data for non US cities/regions
kable(filter(metadata,(is.na(Country.Region) | is.na(Population) )) %>% select(c("Country.Region","Province.State","City")) %>% unique(),caption = "Regions for which either population or Country is NA")
# Drop missing data
metadata<-filter(metadata,!(is.na(Country.Region) | is.na(Population) ))
# Convert remaining pop to numeric
metadata$Population<-as.numeric(metadata$Population)
# Add metadata to cases
Corona_Cases<-merge(Corona_Cases,metadata,all.x = T)
##------------------------------------------
## Compute total and death cases relative to population
##------------------------------------------
Corona_Cases$Total_confirmed_cases.per100<-100*Corona_Cases$Total_confirmed_cases/Corona_Cases$Population
Corona_Cases$Total_confirmed_deaths.per100<-100*Corona_Cases$Total_confirmed_deaths/Corona_Cases$Population
##------------------------------------------
## Filter df for US state-wide stats
##------------------------------------------
Corona_Cases.US_state<-filter(Corona_Cases,Country.Region=="US_state" & Total_confirmed_cases>0 )
kable(table(select(Corona_Cases.US_state,c("Province.State"))),caption = "Number of longitudinal datapoints (total/death) per state")
Corona_Cases.US_state<-merge(Corona_Cases.US_state,ddply(filter(Corona_Cases.US_state,Total_confirmed_cases>100),c("Province.State"),summarise,case100_date_state=min(Date.numeric)))
Corona_Cases.US_state$Days_since_100_state<-Corona_Cases.US_state$Date.numeric-Corona_Cases.US_state$case100_date_state
```
## ANALYSIS
### Q1: What is the trend in cases, mortality across geopgraphical regions?
Plot # of cases vs time
* For each geographical set:
* comparative longitudinal case trend (absolute & log scale)
* comparative longitudinal mortality trend
* death vs total correlation
question | dataset | x | y | color | facet | pch | dimentions
-------- | ------- | - | - | ----- | ----- | --- | ----------
comparative_longitudinal_case_trend | long | time | log_cases | geography | none (case type?) | case_type | [15, 50, 4] geography x (2 scale?) case type
comparative longitudinal case trend|long|time|cases|geography|case_type|?|[15, 50, 4] geography x (2+ scale) case type
comparative longitudinal mortality trend|wide|time|mortality rate|geography|none|none|[15, 50, 4] geography
death vs total correlation|wide|cases|deaths|geography|none|none|[15, 50, 4] geography
```{r, eval=T}
# total cases vs time
# death cases vs time
# mortality rate vs time
# death vs mortality
# death vs mortality
# total & death case vs time (same plot)
#<question> <x> <y> <colored> <facet> <dataset>
## trend in case/deaths over time, comapred across regions <time> <log cases> <geography*> <none> <.wide>
## trend in case/deaths over time, comapred across regions <time> <cases> <geography*> <case_type> <.long>
## trend in mortality rate over time, comapred across regions <time> <mortality rate> <geography*> <none>
## how are death/mortality related/correlated? <time> <log cases> <geography*> <none>
## how are death and case load correlated? <cases> <deaths>
# lm for each?? - > apply lm from each region starting from 100th case. m, b associated with each.
# input: geographical regsion, logcase vs day (100th case)
# output: m, b for each geographical region ID
#total/death on same plot- diffeer by 2 logs, so when plotting log, use pch. when plotting absolute, need to use free scales
#when plotting death and case on same, melt.
#CoronaCases - > filter sets (3)
#world - choose countries with sufficent data
N<-ddply(filter(Corona_Cases,Total_confirmed_cases>100),c("Country.Region"),summarise,n=length(Country.Region))
ggplot(filter(N,n<100),aes(x=n))+
geom_histogram()+
default_theme+
ggtitle("Distribution of number of days with at least 100 confirmed cases for each region")
kable(arrange(N,-n),caption="Sorted number of days with at least 100 confirmed cases")
# Pick top 15 countries with data
max_colors<-12
# find way to fix this- China has diff provences. Plot doesnt look right...
sufficient_data<-arrange(filter(N,!Country.Region %in% c("US_state", "Diamond Princess")),-n)[1:max_colors,]
kable(sufficient_data,caption = paste0("Top ",max_colors," countries with sufficient data"))
Corona_Cases.world<-filter(Corona_Cases,Country.Region %in% c(sufficient_data$Country.Region))
#us
# - by state
Corona_Cases.US<-filter(Corona_Cases,Country.Region=="US" & Total_confirmed_cases>0)
# summarize
#!City %in% c("Unassigned")
# - specific cities
#mortality_rate!=Inf & mortality_rate<=1
Corona_Cases.UScity<-filter(Corona_Cases,Province.State %in% c("Pennsylvania","Maryland","New York","New Jersey") & City %in% c("Bucks","Baltimore City", "New York","Burlington"))
measure_vars_long<-c("Total_confirmed_cases.log","Total_confirmed_cases","Total_confirmed_deaths","Total_confirmed_deaths.log")
melt_arg_list<-list(variable.name = "case_type",value.name = "cases",measure.vars = c("Total_confirmed_cases","Total_confirmed_deaths"))
melt_arg_list$data=NULL
melt_arg_list$data=select(Corona_Cases.world,-ends_with(match = "log"))
Corona_Cases.world.long<-do.call(melt,melt_arg_list)
melt_arg_list$data=select(Corona_Cases.UScity,-ends_with(match = "log"))
Corona_Cases.UScity.long<-do.call(melt,melt_arg_list)
melt_arg_list$data=select(Corona_Cases.US_state,-ends_with(match = "log"))
Corona_Cases.US_state.long<-do.call(melt,melt_arg_list)
Corona_Cases.world.long$cases.log<-log(Corona_Cases.world.long$cases,10)
Corona_Cases.US_state.long$cases.log<-log(Corona_Cases.US_state.long$cases,10)
Corona_Cases.UScity.long$cases.log<-log(Corona_Cases.UScity.long$cases,10)
# what is the current death and total case load for US? For world? For states?
#-absolute
#-log
# what is mortality rate (US, world)
#-absolute
#how is death and case correlated? (US, world)
#-absolute
```
```{r question1, eval=T}
#Corona_Cases.US<-filter(Corona_Cases,Country.Region=="US" & Total_confirmed_cases>0)
#Corona_Cases.US.case100<-filter(Corona_Cases.US, Days_since_100>=0)
# linear model parameters
#(model_fit<-lm(formula = Total_confirmed_cases.log~Days_since_100,data= Corona_Cases.US.case100 ))
#(slope<-model_fit$coefficients[2])
#(intercept<-model_fit$coefficients[1])
# Correlation coefficient
#cor(x = Corona_Cases.US.case100$Days_since_100,y = Corona_Cases.US.case100$Total_confirmed_cases.log)
##------------------------------------------
## Plot World Data
##------------------------------------------
# Timestamp for world
timestamp_plot.world<-paste("Most recent date for which data available:",max(Corona_Cases.world$Date))#timestamp(quiet = T,prefix = "Updated ",suffix = " (EST)")
# Base template for plots
baseplot.world<-ggplot(data=NULL,aes(x=Days_since_100,col=Country.Region))+
default_theme+
scale_color_brewer(type = "qualitative",palette = "Paired")+
ggtitle(paste("Log10 cases over time,",timestamp_plot.world))+
theme(legend.position = "bottom",plot.title = element_text(size=12))
##/////////////////////////
### Plot Longitudinal cases
(Corona_Cases.world.long.plot<-baseplot.world+
geom_point(data=Corona_Cases.world.long,aes(y=cases))+
geom_line(data=Corona_Cases.world.long,aes(y=cases))+
facet_wrap(~case_type,scales = "free_y",ncol=1)+
ggtitle(timestamp_plot.world)
)
(Corona_Cases.world.loglong.plot<-baseplot.world+
geom_point(data=Corona_Cases.world.long,aes(y=cases.log))+
geom_line(data=Corona_Cases.world.long,aes(y=cases.log))+
facet_wrap(~case_type,scales = "free_y",ncol=1)+
ggtitle(timestamp_plot.world))
##/////////////////////////
### Plot Longitudinal mortality rate
(Corona_Cases.world.mortality.plot<-baseplot.world+
geom_point(data=Corona_Cases.world,aes(y=mortality_rate))+
geom_line(data=Corona_Cases.world,aes(y=mortality_rate))+
ylim(c(0,0.3))+
ggtitle(timestamp_plot.world))
##/////////////////////////
### Plot death vs total case correlation
(Corona_Cases.world.casecor.plot<-ggplot(Corona_Cases.world,aes(x=Total_confirmed_cases,y=Total_confirmed_deaths,col=Country.Region))+
geom_point()+
geom_line()+
default_theme+
scale_color_brewer(type = "qualitative",palette = "Paired")+
ggtitle(paste("Log10 cases over time,",timestamp_plot.world))+
theme(legend.position = "bottom",plot.title = element_text(size=12))+
ggtitle(timestamp_plot.world))
### Write polots
write_plot(Corona_Cases.world.long.plot,wd = results_dir)
write_plot(Corona_Cases.world.loglong.plot,wd = results_dir)
write_plot(Corona_Cases.world.mortality.plot,wd = results_dir)
write_plot(Corona_Cases.world.casecor.plot,wd = results_dir)
##------------------------------------------
## Plot US State Data
##-----------------------------------------
baseplot.US<-ggplot(data=NULL,aes(x=Days_since_100_state,col=case_type))+
default_theme+
facet_wrap(~Province.State)+
ggtitle(paste("Log10 cases over time,",timestamp_plot.world))
Corona_Cases.US_state.long.plot<-baseplot.US+geom_point(data=Corona_Cases.US_state.long,aes(y=cases.log))
##------------------------------------------
## Plot US City Data
##-----------------------------------------
Corona_Cases.US.plotdata<-filter(Corona_Cases.US_state,Province.State %in% c("Pennsylvania","Maryland","New York","New Jersey") &
City %in% c("Bucks","Baltimore City", "New York","Burlington") &
Total_confirmed_cases>0)
timestamp_plot<-paste("Most recent date for which data available:",max(Corona_Cases.US.plotdata$Date))#timestamp(quiet = T,prefix = "Updated ",suffix = " (EST)")
city_colors<-c("Bucks"='#beaed4',"Baltimore City"='#386cb0', "New York"='#7fc97f',"Burlington"='#fdc086')
##/////////////////////////
### Plot death vs total case correlation
(Corona_Cases.city.loglong.plot<-ggplot(melt(Corona_Cases.US.plotdata,measure.vars = c("Total_confirmed_cases.log","Total_confirmed_deaths.log"),variable.name = "case_type",value.name = "cases"),aes(x=Date,y=cases,col=City,pch=case_type))+
geom_point(size=4)+
geom_line()+
default_theme+
#facet_wrap(~case_type)+
ggtitle(paste("Log10 total and death cases over time,",timestamp_plot))+
theme(legend.position = "bottom",plot.title = element_text(size=12))+
scale_color_manual(values = city_colors))
(Corona_Cases.city.long.plot<-ggplot(filter(Corona_Cases.US.plotdata,Province.State !="New York"),aes(x=Date,y=Total_confirmed_cases,col=City))+
geom_point(size=4)+
geom_line()+
default_theme+
facet_grid(~Province.State,scales = "free_y")+
ggtitle(paste("MD, PA, NJ total cases over time,",timestamp_plot))+
theme(legend.position = "bottom",plot.title = element_text(size=12))+
scale_color_manual(values = city_colors))
(Corona_Cases.city.mortality.plot<-ggplot(Corona_Cases.US.plotdata,aes(x=Date,y=mortality_rate,col=City))+
geom_point(size=3)+
geom_line(size=2)+
default_theme+
ggtitle(paste("Mortality rate (deaths/total) over time,",timestamp_plot))+
theme(legend.position = "bottom",plot.title = element_text(size=12))+
scale_color_manual(values = city_colors))
(Corona_Cases.city.casecor.plot<-ggplot(filter(Corona_Cases.US.plotdata,Province.State !="New York"),aes(x=Total_confirmed_deaths,y=Total_confirmed_cases,col=City))+
geom_point(size=3)+
geom_line(size=2)+
default_theme+
ggtitle(paste("Correlation of death vs total cases,",timestamp_plot))+
theme(legend.position = "bottom",plot.title = element_text(size=12))+
scale_color_manual(values = city_colors))
(Corona_Cases.city.long.normalized.plot<-ggplot(filter(Corona_Cases.US.plotdata,Province.State !="New York"),aes(x=Date,y=Total_confirmed_cases.per100,col=City))+
geom_point(size=4)+
geom_line()+
default_theme+
facet_grid(~Province.State)+
ggtitle(paste("MD, PA, NJ total cases over time per 100 people,",timestamp_plot))+
theme(legend.position = "bottom",plot.title = element_text(size=12))+
scale_color_manual(values = city_colors))
write_plot(Corona_Cases.city.long.plot,wd = results_dir_custom)
write_plot(Corona_Cases.city.loglong.plot,wd = results_dir_custom)
write_plot(Corona_Cases.city.mortality.plot,wd = results_dir_custom)
write_plot(Corona_Cases.city.casecor.plot,wd = results_dir_custom)
write_plot(Corona_Cases.city.long.normalized.plot,wd = results_dir_custom)
```
### Q2: What is the predicted number of cases?
#### What is the prediction of COVID-19 based on model thus far?
Additional questions:
WHy did it take to day 40 to start a log linear trend?
How long will it be till x number of cases?
When will the plateu happen?
Are any effects noticed with social distancing? Delays
```{r prediction, eval=F}
##------------------------------------------
## Prediction and Prediction Accuracy
##------------------------------------------
# What is the predict # of cases for the next few days?
# How is the model performing historically?
# Formula for # of cases by x days
paste0("log10_total_cases = ",slope,"*days + ",intercept)
paste0("total_cases = 10^(",slope,"*days + ",intercept,")")
#Days untill... cases:
# 2.5k, 5k and 1M:
paste0("2.5k cases is ",(log(2.5E5,10) - intercept)/slope," days")
paste0("5k cases is ",(log(5E5,10)- intercept)/slope," days")
paste0("1M cases is ",(log(1E6,10)- intercept)/slope," days")
head(filter(Corona_Cases.raw,Country.Region=="US"))
today_num<-max(Corona_Cases.US$Days_since_100)
predicted_days<-today_num+c(1,2,3,7)
#mods = dlply(mydf, .(x3), lm, formula = y ~ x1 + x2)
#today:
Corona_Cases.US[Corona_Cases.US$Days_since_100==(today_num-1),]
Corona_Cases.US[Corona_Cases.US$Days_since_100==today_num,]
Corona_Cases.US$type<-"Historical"
names(Corona_Cases)
Corona_Cases_wprediction<-rbind.fill(Corona_Cases.US,data.frame(Code="USA",type="MAR26_prediction",prediction_model(m=slope,b=intercept,days = predicted_days)))
Corona_Cases.US.prediction<-Corona_Cases_wprediction
prediction_values<-prediction_model(m=slope,b=intercept,days = predicted_days)$Total_confirmed_cases
histoical_model<-data.frame(date=today_num,m=slope,b=intercept)
# model for previous y days
historical_model_predictions<-data.frame(day_x=NULL,Days_since_100=NULL,Total_confirmed_cases=NULL,Total_confirmed_cases.log=NULL)
for(i in c(1,2,3,4,5,6,7,8,9,10)){
#i<-1
day_x<-today_num-i # 1, 2, 3, 4
day_x_nextweek<-day_x+c(1,2,3)
model_fit_x<-lm(data = filter(Corona_Cases.US.case100,Days_since_100 < day_x),formula = Total_confirmed_cases.log~Days_since_100)
prediction_day_x_nextweek<-prediction_model(m = model_fit_x$coefficients[2],b = model_fit_x$coefficients[1],days = day_x_nextweek)
prediction_day_x_nextweek$type<-"Predicted"
acutal_day_x_nextweek<-filter(Corona_Cases.US,Days_since_100 %in% day_x_nextweek) %>% select(c(Days_since_100,Total_confirmed_cases,Total_confirmed_cases.log))
acutal_day_x_nextweek$type<-"Historical"
historical_model_predictions.i<-data.frame(day_x=day_x,rbind(acutal_day_x_nextweek,prediction_day_x_nextweek))
historical_model_predictions<-rbind(historical_model_predictions.i,historical_model_predictions)
}
historical_model_predictions.withHx<-rbind.fill(historical_model_predictions,data.frame(Corona_Cases.US,type="Historical"))
historical_model_predictions.withHx$Total_confirmed_cases.log2<-log(historical_model_predictions.withHx$Total_confirmed_cases,2)
#TODO: fix case_type.. are we predicting deaths too?
#TODO: better analysis of death rate!
(historical_model_predictions.plot<-ggplot(historical_model_predictions.withHx,aes(x=Days_since_100,y=Total_confirmed_cases.log,col=type))+
geom_point(size=3)+
default_theme+
theme(legend.position = "bottom")+
#geom_abline(slope = slope,intercept =intercept,lty=2)+
#facet_wrap(~case_type,ncol=1)+
scale_color_manual(values = c("Historical"="#377eb8","Predicted"="#e41a1c")))
write_plot(historical_model_predictions.plot,wd=results_dir)
```
```{r question2, eval=F}
##------------------------------------------
## filter input_data1
##------------------------------------------
input_data1.filter<-fitler(input_data1,col1=="foo")
##------------------------------------------
##------------------------------------------
## sub question 1
##------------------------------------------
table(input_data1.filter$col<5)
##------------------------------------------
##------------------------------------------
## sub question 2
##------------------------------------------
table(input_data1.filter$col<10)
##------------------------------------------
##------------------------------------------
## plot data
##------------------------------------------
(input_data1.filter.plot<-ggplot(input_data1.filter,aes(x=col1,y=col2.log))+
geom_point()+
default_plot_theme)
write_plot(input_data1.filter.plot,wd=results_dir)
##------------------------------------------
results_dir
```
### Q3: What is the effect on social distancing, descreased mobility on case load?
Load data from Google which compoutes % change in user mobility relative to baseline for
* Recreation
* Workplace
* Residence
* Park
* Grocery
Data from https://www.google.com/covid19/mobility/
```{r mobility, eval=T}
# See pre-processing section for script on gathering mobility data
# UNDER DEVELOPMENT
# TODO convert % to numeric in mobility data
# TODO standardize headers in mobility data
# TODO standardize counties in mobility data to JHU source
# TODO normalize case load to population for mobility data
# TODO automate get_mobility.py script so most recent data is availble
mobility<-read.csv("/Users/stevensmith/Projects/MIT_COVID19/mobility.csv",header = T,stringsAsFactors = F)
#mobility$Retail_Recreation<-as.numeric(sub(mobility$Retail_Recreation,pattern = "%",replacement = ""))
#mobility$Workplace<-as.numeric(sub(mobility$Workplace,pattern = "%",replacement = ""))
#mobility$Residential<-as.numeric(sub(mobility$Residential,pattern = "%",replacement = ""))
##------------------------------------------
## Show relationship between mobility and caseload
##------------------------------------------
mobility$County<-gsub(mobility$County,pattern = " County",replacement = "")
Corona_Cases.US_state.mobility<-merge(Corona_Cases.US_state,plyr::rename(mobility,c("State"="Province.State","County"="City")))
#Corona_Cases.US_state.tmp<-merge(metadata,Corona_Cases.US_state.tmp)
# Needs to happen upsteam, see todos
#Corona_Cases.US_state.tmp$Total_confirmed_cases.perperson<-Corona_Cases.US_state.tmp$Total_confirmed_cases/as.numeric(Corona_Cases.US_state.tmp$Population)
mobility_measures<-c("Retail_Recreation","Grocery_Pharmacy","Parks","Transit","Workplace","Residential")
plot_data<-filter(Corona_Cases.US_state.mobility, Date.numeric==max(Corona_Cases.US_state$Date.numeric) ) %>% melt(measure.vars=mobility_measures)
plot_data$value<-as.numeric(gsub(plot_data$value,pattern = "%",replacement = ""))
plot_data<-filter(plot_data,!is.na(value))
(mobility.plot<-ggplot(filter(plot_data,Province.State %in% c("Pennsylvania","Maryland","New Jersey","California","Delaware","Connecticut")),aes(y=Total_confirmed_cases.per100,x=value))+geom_point()+
facet_grid(Province.State~variable,scales = "free")+
xlab("Mobility change from baseline (%)")+
ylab(paste0("Confirmed cases per 100 people(Today)"))+
default_theme+
ggtitle("Mobility change vs cases"))
(mobility.global.plot<-ggplot(plot_data,aes(y=Total_confirmed_cases.per100,x=value))+geom_point()+
facet_wrap(~variable,scales = "free")+
xlab("Mobility change from baseline (%)")+
ylab(paste0("Confirmed cases (Today) per 100 people"))+
default_theme+
ggtitle("Mobility change vs cases"))
plot_data.permobility_summary<-ddply(plot_data,c("Province.State","variable"),summarise,cor=cor(y =Total_confirmed_cases.per100,x=value),median_change=median(x=value)) %>% arrange(-abs(cor))
kable(plot_data.permobility_summary,caption = "Ranked per-state mobility correlation with total confirmed cases")
# sanity check
ggplot(filter(plot_data,Province.State %in% c("Pennsylvania","Maryland","New Jersey","California","Delaware","Connecticut")),aes(x=Total_confirmed_cases.per100,fill=variable))+geom_histogram()+
facet_grid(~Province.State)+
default_theme+
theme(legend.position = "bottom")
write_plot(mobility.plot,wd = results_dir)
write_plot(mobility.global.plot,wd = results_dir)
# TODO secondary question: rank greatest to least mobility
(plot_data.permobility_summary.plot<-ggplot(plot_data.permobility_summary,aes(x=variable,y=median_change))+
geom_jitter(size=2,width=.2)+
#geom_jitter(data=plot_data.permobility_summary %>% arrange(-abs(median_change)) %>% head(n=15),aes(col=Province.State),size=2,width=.2)+
default_theme+
ggtitle("Per-Sate Median Change in Mobility")+
xlab("Mobility Meaure")+
ylab("Median Change from Baseline"))
write_plot(plot_data.permobility_summary.plot,wd = results_dir)
```
# DELIVERABLE MANIFEST
The following link to commited documents pushed to github. These are provided as a convienence, but note this is a manual process. The generation of reports, plots and tables is not coupled to the execution of this markdown.
## Report
This report, html & pdf
## Plots
```{r}
github_root<-"https://github.com/sbs87/coronavirus/blob/master/"
link<-paste0(github_root,"results/Corona_Cases.world.casecor.plot.png")
section_ref<-'Q3'
plot_handle<-c("Corona_Cases.world.casecor.plot","Corona_Cases.world.long.plot")
name<-"World total & death cases, correlation"
deliverable_manifest<-data.frame(
name=c("World total & death cases, correlation",
"World total & death cases, longitudinal"),
plot_handle=plot_handle,
link=paste0(github_root,"results/",plot_handle,".png")
)
(tmp<-data.frame(row_out=apply(deliverable_manifest,MARGIN = 1,FUN = function(x) paste(x[1],x[2],x[3],sep=" | "))))
row_out<-apply(tmp, 2, paste, collapse="\t\n")
```
name | handle | link
---- | ------ | ----
`r row_out`
## Tables
# CONCLUSION
Overall, the trends of COVID-19 cases is no longer in log-linear phase for world or U.S. (but some regions like MD are still in the log-linear phase). Mortality rate (deaths/confirmed RNA-based cases) is >1%, with a range depending on region. Mobility is not a strong indicator of caseload (U.S. data).
See table below for detailed breakdown.
Question | Answer
------------- | -------------
<a href="#Q3: What is the effect on social distancing, descreased mobility on case load?">What is the effect on social distancing, descreased mobility on case load?</a><br> | There is not a strong apparent effect on decreased mobility (work, grocery, retail) or increased mobility (at residence, parks) on number of confirmed cases, either as a country (U.S.) or state level. California appears to have one of the best correlations, but this is a mixed bag
<a href="#Q1: What is the trend in cases, mortality across geopgraphical regions?">What is the trend in cases, mortality across geopgraphical regions?</a><br> | The confirmed total casees and mortality is overall log-linear for most countries, with a trailing off beginning for most (inlcuding U.S.). On the state level, NY, NJ, PA starting to trail off; MD is still in log-linear phase. Mortality and case load are highly correlated for NY, NJ, PA, MD. The mortality rate flucutates for a given region, but is about 3% overall.
#END
End: `r paste(timestamp())`
Cheatsheet:
http://rmarkdown.rstudio.com>
# TODO
* mkdir the results dir if it doesn't exist
* make ggplot a dependency for plot.utils?
* automated way of downloading daily data
* fix plot_utils, add dataset and documentation
* Auto git mv the new data?
# Sandbox
```{r eval=F}
##TODO:
# Geographical heatmap!
install.packages("maps")
library(maps)
library
mi_counties <- map_data("county", "pennsylvania") %>%
select(lon = long, lat, group, id = subregion)
head(mi_counties)
ggplot(mi_counties, aes(lon, lat)) +
geom_point(size = .25, show.legend = FALSE) +
coord_quickmap()
mi_counties$cases<-1:2226
name_overlaps(metadata,Corona_Cases.US_state)
tmp<-merge(Corona_Cases.US_state,metadata)
ggplot(filter(tmp,Province.State=="Pennsylvania"), aes(Long, Lat, group = as.factor(City))) +
geom_polygon(aes(fill = Total_confirmed_cases), colour = "grey50") +
coord_quickmap()
```
<center>
![id](/Users/stevensmith/Desktop/header.png)
<p>https://stevenbsmith.net</p>
</center>
<script type="text/javascript">
// When the document is fully rendered...
$(document).ready(function() {
// ...select all header elements...
$('h1, h2, h3, h4, h5').each(function() {
// ...and add an id to them corresponding to their 'titles'
$(this).attr('id', $(this).html());
});
});
</script>