Summary

Row

confirmed

343,091

death

9,900 (2.9%)

Growth rate

0.12

Doubling time for last 15 days data

17.711 days

Row

Daily cumulative cases by type (India only)

Comparison

Column

Daily new confirmed cases

Cases distribution by type

Projections

SIR

Row

confirmed

1.194991

Row

Daily infections

Map

World map of cases (use + and - icons to zoom in/out)

About

The Coronavirus Dashboard: the case of India

This Coronavirus dashboard: the case of India provides an overview of the 2019 Novel Coronavirus COVID-19 (2019-nCoV) epidemic for India. This dashboard is built with R using the R Makrdown framework and was adapted from this dashboard by Rami Krispin. Code also modified from https://www.antoinesoetewey.com/files/coronavirus-dashboard.html Code

Data

The input data for this dashboard is the dataset available from the {coronavirus} R package. Make sure to download the development version of the package to have the latest data:

install.packages("devtools")
devtools::install_github("RamiKrispin/coronavirus")

The data and dashboard are refreshed on a daily basis.

The raw data is pulled from the Johns Hopkins University Center for Systems Science and Engineering (JHU CCSE) Coronavirus repository.

---
title: "Coronavirus in India"
author: "VC"
output: 
  flexdashboard::flex_dashboard:
    orientation: rows
    # social: ["facebook", "twitter", "linkedin"]
    source_code: embed
    vertical_layout: fill
---

```{r setup, include=FALSE}
#------------------ Packages ------------------
library(flexdashboard)
library("devtools")
library(dplyr)

  # download.file(url="https://raw.githubusercontent.com/RamiKrispin/coronavirus/master/csv/coronavirus.csv",destfile ="/Users/Vratika/Desktop/Epidemics/datacvod.csv" )
coronavirus<- read_csv("datacvod.csv")

#devtools::install_github("RamiKrispin/coronavirus", force = TRUE)



###devtools::install_github("RamiKrispin/coronavirus")

library(coronavirus)


#coronavirus::update_datasets(silence = TRUE)

#View(coronavirus)
# max(coronavirus$date)


`%>%` <- magrittr::`%>%`
#------------------ Parameters ------------------
# Set colors
# https://www.w3.org/TR/css-color-3/#svg-color
confirmed_color <- "mediumvioletred"
active_color <- "black"
recovered_color <- "darkseagreen"
death_color <- "darkorange"
doubling_color <- "darkblue"
purple<-"purple"
#------------------ Data ------------------

# df <- coronavirus %>%
#   # dplyr::filter(date == max(date)) %>%
#   dplyr::filter(country == "India") %>% 
#   dplyr::group_by( type) %>%
#   dplyr::summarise(total = sum(cases)) %>%
#   tidyr::pivot_wider(
#     names_from = type,
#     values_from = total
#   ) %>%
#   # dplyr::mutate(unrecovered = confirmed - ifelse(is.na(recovered), 0, recovered) - ifelse(is.na(death), 0, death)) %>%
#   dplyr::mutate(unrecovered = confirmed - ifelse(is.na(death), 0, death)) %>%
#   dplyr::arrange(-confirmed) %>%
#   dplyr::ungroup() %>%
#   dplyr::mutate(country = dplyr::if_else(country == "United Arab Emirates", "UAE", country)) %>%
#   dplyr::mutate(country = dplyr::if_else(country == "Mainland China", "China", country)) %>%
#   dplyr::mutate(country = dplyr::if_else(country == "North Macedonia", "N.Macedonia", country)) %>%
#   dplyr::mutate(country = trimws(country)) %>%
#   dplyr::mutate(country = factor(country, levels = country))


df_daily <- coronavirus %>%
  dplyr::filter(country == "India") %>%
  dplyr::group_by(date, type) %>%
  dplyr::summarise(total = sum(cases, na.rm = TRUE)) %>%
  tidyr::pivot_wider(
    names_from = type,
    values_from = total
  ) %>%
  dplyr::arrange(date) %>%
  dplyr::ungroup() %>%
  #dplyr::mutate(active = confirmed - death - recovered) %>%
  dplyr::mutate(active = confirmed - death) %>%
  dplyr::mutate(
    confirmed_cum = cumsum(confirmed),
    death_cum = cumsum(death),
    # recovered_cum = cumsum(recovered),
    active_cum = cumsum(active)
  )


df1 <- coronavirus %>% dplyr::filter(date == max(date))
```

```{r }
library(dplyr)

df_ind <- coronavirus %>% 
 # lubridate::ymd(date) %>% 
  # dplyr::filter(date == max(date)) %>%
  dplyr::filter(country == "India" ) %>% 
  dplyr::filter(cases!=0) %>% 
  dplyr::filter(date >"2020-03-04") %>% 
  arrange(date) 
 df_ind<-df_ind %>%   dplyr::mutate(day=1:nrow(df_ind)) %>% 
  tidyr::pivot_wider(names_from=type,values_from=cases)#|
# #select only confirmed cases
 df_ind_conf<-df_ind %>% 
  dplyr::filter(!is.na(confirmed)) %>% select(day,date,confirmed) %>% mutate(total_cases= cumsum(confirmed))

  #   country == "China" |
  #   country == "Italy" |
  #   country == "Thailand"|country == "US" ) %>%
  # dplyr::group_by(country, type) %>%
  # dplyr::summarise(total = sum(cases)) %>%
  # tidyr::pivot_wider(
  #   names_from = type,
  #   values_from = total
  # ) %>%
  # # dplyr::mutate(unrecovered = confirmed - ifelse(is.na(recovered), 0, recovered) - ifelse(is.na(death), 0, death)) %>%
  # dplyr::mutate(unrecovered = confirmed - ifelse(is.na(death), 0, death)) %>%
  # dplyr::arrange(confirmed) %>%
  # dplyr::ungroup() %>%
  # dplyr::mutate(country = dplyr::if_else(country == "United Arab Emirates", "UAE", country)) %>%
  # dplyr::mutate(country = dplyr::if_else(country == "Mainland China", "China", country)) %>%
  # dplyr::mutate(country = dplyr::if_else(country == "North Macedonia", "N.Macedonia", country)) %>%
  # dplyr::mutate(country = trimws(country)) %>%
  # dplyr::mutate(country = factor(country, levels = country))
###growth rate##################
#Estimate the ratio method , this just calculated pop at t+1/pop at t
#taking only last 15 days doubling time
df_ind_conf<-df_ind %>% 
  dplyr::filter(!is.na(confirmed)) %>%  dplyr::select(day,date,confirmed)%>%
  dplyr:: mutate(total_cases= cumsum(confirmed))
  
  #dplyr::filter(row_number() >= (n() - 15)) #last 15 days
 df_ind_conf.last15<- df_ind_conf %>% tail(15)
 lambda.l15 = df_ind_conf.last15$total_cases[-1]/ df_ind_conf.last15$total_cases[-length(df_ind_conf.last15$total_cases)] #The #"-
 r.last15 = mean(log(lambda.l15), na.rm = T)
  
lambda = df_ind_conf$total_cases[-1]/ df_ind_conf$total_cases[-length(df_ind_conf$total_cases)] #The #"-" notation excludes specified entry of a vector
#lambda
#mean lambda
#mean(lambda, na.rm = T)
#sd(lambda, na.rm = T)
#Mean and sd of continuous time disease growth rate
r = mean(log(lambda), na.rm = T)
sd_r = sd(log(lambda), na.rm = T)


#generate a function that takes a value of r and runs one stochastic simulation
#so we can use both means and variance of r
exp.stoch = function(r_sim) {
  for (i in 1:time) {
    N_sim[i + 1] = N_sim[i] * exp(r_sim[i]) #this is the exponential growth formula
    #N at t+1 = N at t*exp(r*t)
  }
  return(N_sim)
}
```


```{r}
#Moving average
# df_daily.7 <- coronavirus %>%
#   dplyr::filter(country == "India") %>%
#    dplyr::filter(cases!=0) %>% 
#   dplyr::group_by(date, type) %>%
#   dplyr::summarise(total = sum(cases, na.rm = TRUE)) %>%
#   tidyr::pivot_wider(
#     names_from = type,
#     values_from = total
#   ) %>%
#   dplyr::arrange(date) %>%
#   dplyr::ungroup() %>%
#  
#   dplyr::filter(date >"2020-03-04") %>% 
#   dplyr::arrange(date)  
# 
#  df_ind.daily.7<-  df_daily.7  %>%   dplyr::mutate(day=1:nrow(df_daily.7 )) %>% 
#      dplyr::filter(!is.na(confirmed)) %>%    dplyr::select(day,date,confirmed) %>%    dplyr::mutate(total_cases= cumsum(confirmed))
# 
# 
# df7.1 <-  df_ind.daily.7 %>%dplyr::select(total_cases)
# #df7.2<- cumsum(df7.1, list(0:3),sum,fill=1:3)
# #df7.2<-colSums(matrix(df7.1$total_cases, nrow=6))
# df7.2<-as.data.frame(rollapply(df7.1, width=4, FUN=sum, by=4, partial=T, align="right"))
# df7.2$days<-seq(1,4*nrow(df7.2),4)
# lambda.df7.2 = df7.2$total_cases[-1]/ df7.2$total_cases[-length(df7.2$total_cases)] #The #"-
#  r.last.7day = mean(log(lambda.df7.2), na.rm = T)
#   
  
```


```{r}
# ##############################################
# #          STEP 1: DEFINE ODEs 
# 
# #############################################
# SIR = function(t, y, params) {
#   with(as.list(c(y, params)), {
#     incid = Beta * S * I#Just for convenience
#     dS.dt = -incid/N
#     dE.dt=  incid/N - alpha*E
#     dI.dt = alpha*E - gamma*I
#    # dI.dt = incid - gamma * I
#     dR.dt = gamma * I
#     return(list(c(dS.dt, dE.dt,dI.dt, dR.dt)))
#   })
# }
# 
# #################################################
# #       STEP 2: SUPPLY INITIAL CONDITIONS
# #################################################
# 
# # Initial conditions: starting values of state variables 
# # (S, I and R)
# ########################################################
# logN = log(1700000000 ) #12447000
# N = exp(logN)
# #N= 5000000
# #Total N
# 
# 
# 
# I = 10#24530/N #
# R = 0#6278/N
# E =  1#1/N
# S = N-I-R-E #N/N -E- I-R
# R0=2.2
# #N = S + I + R #Total pop size is the sum of the S, I and R
# 
# # Need *named* initial conditions. That is, put initial values of
# # S, I and R and give it a name. Here, we are calling the vector
# # of initial values "y"
# 
# y = c(S = S, I = I,E=E, R = R)
# 
# ###########################################################
# #            STEP 3: SUPPLY PARAMETER VALUES 
# #
# #Parameters: values of Beta and gamma
# ##########################################################
# # β and γ represented the probability of a susceptible-infected contact resulting in a new infection
# #and the probability of an infected case recovering and moving into the resistant phase, respectively.
# 
# gamma = 1/3# 1/ time for healing 0.125#rate of recovery=8 days for milf 1/3.38#1/5 #0.08
# social_distancing=1
# Beta=  1.9/3#social_distancing*1.9/3
# alpha= 1/5.2 #incubation#beta= Rt/T infection
# 
# #beta is the parameter to change for social distancing
# #reduce Rt and beta would be lower
# #gamma depends on disease, cant change unless cure appears
# #beta depends on social distancing
# #
# params = list(Beta = Beta, gamma = gamma, alpha=alpha)
# 
# #time over which to solve the odes
# t = seq(0,100, by =1)
# #Initial population vector (initial conditions)
# 
# ########################################################
# #            STEP 4a: SOLVE THE ODEs AND PLOT RESULTS
# ########################################################
# 
# 
# library(deSolve)
# results0 = ode(
#   y = y,
#   times = t,
#   func = SIR,
#   parms = params
# )
# 
# 
# #Change the data structure to data.frame so it can be plotted
# results = data.frame(results0)
# results
# ########################################################
# #            STEP 4b: EXAMINE AND PLOT THE RESULTS
# ########################################################
# 
# head(results)
# tail(results)
# #785836.2*0.02
# 
# matplot(
#   t,
#   results[, -c(1,2,4)],
#   type = 'l',
#   lty = 1:3,
#   col = 1:3,
#   xlab = "Time",
#   ylab = "S, I or R",
#   cex = 1.5,
#   cex.main = 1.5,
#   cex.lab = 1.5,
#   lwd = 2,
#   cex.axis = 1.5,
#    ylim=c(0,10e+2)
# )
# legend(
#   'right',
#   c( 'I','R'),
#   lty = 1:3,
#   col = 1:3,
#   bty = 'n',
#   lwd = 2,
#   cex = 1.5
# )


```






Summary
=======================================================================

Row {data-width=200}
-----------------------------------------------------------------------

### confirmed {.value-box}

```{r}

valueBox(
  value = paste(format(sum(df_daily$confirmed), big.mark = ","), "", sep = " "),
  caption = "Total confirmed cases today",
  #icon = "fas fa-user-md",
  color = confirmed_color
)
```
















### death {.value-box}

```{r}

valueBox(
  value = paste(format(sum(df_daily$death, na.rm = TRUE), big.mark = ","), " (",
    round(100 * sum(df_daily$death, na.rm = TRUE) / sum(df_daily$confirmed), 1),
    "%)",
    sep = ""
  ),
  caption = "Death cases (death rate) today",
 # icon = "fas fa-heart-broken",
  color = death_color
)
```


### Growth rate {.value-box}
```{r }
r = mean(log(lambda), na.rm = T)
valueBox(
  value = paste(format(round(r,2)) ),
  caption = "Growth rate today",
   icon = "fas fa-heart-broken",
  
  color = doubling_color
)
```


### Doubling time for last 15 days data {.value-box}
```{r }

valueBox(
  value = paste(
     round(log(2)/r.last15, 3),
  "days" ),
  caption = "Doubling period (last 15 days)",
   icon = "fas fa-heart-broken",
  
  color = purple
)
```

Row 
-----------------------------------------------------------------------

### **Daily cumulative cases by type** (India only)
    
```{r}
plotly::plot_ly(data = df_daily) %>%
  plotly::add_trace(
    x = ~date,
    # y = ~active_cum,
    y = ~confirmed_cum,
    type = "scatter",
    mode = "lines+markers",
    # name = "Active",
    name = "Confirmed",
    line = list(color = active_color),
    marker = list(color = active_color)
  ) %>%
  plotly::add_trace(
    x = ~date,
    y = ~death_cum,
    type = "scatter",
    mode = "lines+markers",
    name = "Death",
    line = list(color = death_color),
    marker = list(color = death_color)
  ) %>%
  plotly::add_annotations(
    x = as.Date("2020-01-30"),
    y = 1,
    text = paste("First case"),
    xref = "x",
    yref = "y",
    arrowhead = 5,
    arrowhead = 3,
    arrowsize = 1,
    showarrow = TRUE,
    ax = -10,
    ay = -90
  ) %>%
  plotly::add_annotations(
    x = as.Date("2020-03-12"),
    y = 3,
    text = paste("First death"),
    xref = "x",
    yref = "y",
    arrowhead = 5,
    arrowhead = 3,
    arrowsize = 1,
    showarrow = TRUE,
    ax = -90,
    ay = -90
  ) %>%
  plotly::add_annotations(
    x = as.Date("2020-03-24"),
    y = 14,
    text = paste(
      "New containment",
      "",
      "measures"
    ),
    xref = "x",
    yref = "y",
    arrowhead = 5,
    arrowhead = 3,
    arrowsize = 1,
    showarrow = TRUE,
    ax = -10,
    ay = -90
  ) %>%
  plotly::add_annotations(
    x = as.Date("2020-04-14"),
    y = 14,
    text = paste(
      "Cont. ",
      "",
     "ext1 "
    ),
    xref = "x",
    yref = "y",
    arrowhead = 5,
    arrowhead = 3,
    arrowsize = 1,
    showarrow = TRUE,
    ax = -10,
    ay = -90
  ) %>% 
  plotly::add_annotations(
    x = as.Date("2020-05-04"),
    y = 14,
    text = paste(
      "Cont. ",
      "",
      "ext2."
    ),
    xref = "x",
    yref = "y",
    arrowhead = 5,
    arrowhead = 3,
    arrowsize = 1,
    showarrow = TRUE,
    ax = -10,
    ay = -90
  ) %>% 
  plotly::add_annotations(
    x = as.Date("2020-05-18"),
    y = 14,
    text = paste(
      "Cont. ",
      "",
      "ext3."
    ),
    xref = "x",
    yref = "y",
    arrowhead = 5,
    arrowhead = 3,
    arrowsize = 1,
    showarrow = TRUE,
    ax = -10,
    ay = -90
  ) %>%
  plotly::add_annotations(
    x = as.Date("2020-06-01"),
    y = 14,
    text = paste(
      "Cont. ",
      "",
      "ended."
    ),
    xref = "x",
    yref = "y",
    arrowhead = 5,
    arrowhead = 3,
    arrowsize = 1,
    showarrow = TRUE,
    ax = -10,
    ay = -90
  ) %>% 
  plotly::layout(
    title = "",
    yaxis = list(title = "Cumulative number of cases"),
    xaxis = list(title = "Date"),
    legend = list(x = 0.1, y = 0.9),
    hovermode = "compare"
  )
```

Comparison
=======================================================================


Column {data-width=400}
-------------------------------------


### **Daily new confirmed cases**
    
```{r}
daily_confirmed <- coronavirus %>%
  dplyr::filter(type == "confirmed") %>%
  dplyr::filter(date >= "2020-02-03") %>%
  dplyr::mutate(country = country) %>%
  dplyr::group_by(date, country) %>%
  dplyr::summarise(total = sum(cases)) %>%
  dplyr::ungroup() %>%
  tidyr::pivot_wider(names_from = country, values_from = total)

#----------------------------------------
# Plotting the data

daily_confirmed %>%
  plotly::plot_ly() %>%
  plotly::add_trace(
    x = ~date,
    y = ~India,
    type = "scatter",
    mode = "lines+markers",
    name = "India"
  ) %>%
  plotly::add_trace(
    x = ~date,
    y = ~US,
    type = "scatter",
    mode = "lines+markers",
    name = "U.S.A"
  ) %>%
  # plotly::add_trace(
  #   x = ~date,
  #   y = ~Spain,
  #   type = "scatter",
  #   mode = "lines+markers",
  #   name = "Spain"
  # ) %>%
  plotly::add_trace(
    x = ~date,
    y = ~Italy,
    type = "scatter",
    mode = "lines+markers",
    name = "Italy"
  ) %>%

  # plotly::add_trace(
  #   x = ~date,
  #   y = ~ "Korea, South" ,
  #   type = "scatter",
  #   mode = "lines+markers",
  #   name = "South Korea"
  # ) %>%
 
  plotly::add_trace(
    x = ~date,
    y = ~Thailand,
    type = "scatter",
    mode = "lines+markers",
    name = "Thailand"
  ) %>%
   plotly::add_trace(
    x = ~date,
    y = ~China,
    type = "scatter",
    mode = "lines+markers",
    name = "China"
  ) %>% 
  plotly::layout(
    title = "",
    legend = list(x = 0.1, y = 0.9),
    yaxis = list(title = "Number of new confirmed cases"),
    xaxis = list(title = "Date"),
    # paper_bgcolor = "black",
    # plot_bgcolor = "black",
    # font = list(color = 'white'),
    hovermode = "compare",
    margin = list(
      # l = 60,
      # r = 40,
      b = 10,
      t = 10,
      pad = 2
    )
  )
```
 
### **Cases distribution by type**

```{r daily_summary}
df_EU <- coronavirus %>%
  # dplyr::filter(date == max(date)) %>%
  dplyr::filter(country == "India" |
    country == "China" |
    country == "Italy" |
    country == "Thailand"|country == "US" ) %>%
  dplyr::group_by(country, type) %>%
  dplyr::summarise(total = sum(cases)) %>%
  tidyr::pivot_wider(
    names_from = type,
    values_from = total
  ) %>%
  # dplyr::mutate(unrecovered = confirmed - ifelse(is.na(recovered), 0, recovered) - ifelse(is.na(death), 0, death)) %>%
  dplyr::mutate(unrecovered = confirmed - ifelse(is.na(death), 0, death)) %>%
  dplyr::arrange(confirmed) %>%
  dplyr::ungroup() %>%
  dplyr::mutate(country = dplyr::if_else(country == "United Arab Emirates", "UAE", country)) %>%
  dplyr::mutate(country = dplyr::if_else(country == "Mainland China", "China", country)) %>%
  dplyr::mutate(country = dplyr::if_else(country == "North Macedonia", "N.Macedonia", country)) %>%
  dplyr::mutate(country = trimws(country)) %>%
  dplyr::mutate(country = factor(country, levels = country))

plotly::plot_ly(
  data = df_EU,
  x = ~country,
  # y = ~unrecovered,
  y = ~ confirmed,
  # text =  ~ confirmed,
  # textposition = 'auto',
  type = "bar",
  name = "Confirmed",
  marker = list(color = "cyan")
) %>%
  plotly::add_trace(
    y = ~death,
    # text =  ~ death,
    # textposition = 'auto',
    name = "Death",
    marker = list(color = "purple")
  ) %>%
  plotly::layout(
    barmode = "dodge",
    yaxis = list(title = "Total cases"),
    xaxis = list(title = ""),
    hovermode = "compare",
    margin = list(
      # l = 60,
      # r = 40,
      b = 10,
      t = 10,
      pad = 2
    )
  )
```






Projections
=======================================================================





    


```{r}
library(dplyr)

df_ind <- coronavirus %>% 
 # lubridate::ymd(date) %>% 
  # dplyr::filter(date == max(date)) %>%
  dplyr::filter(country == "India" ) %>% 
  dplyr::filter(cases!=0) %>% 
  dplyr::filter(date >"2020-03-04") %>% 
  dplyr::arrange(date) 
df_ind<-df_ind %>%   dplyr::mutate(day=1:nrow(df_ind)) %>% 
  tidyr::pivot_wider(names_from=type,values_from=cases)#|
#select only confirmed cases
df_ind_conf<-df_ind %>% 
  dplyr::filter(!is.na(confirmed)) %>% dplyr::select(day,date,confirmed) %>% dplyr::mutate(total_cases= cumsum(confirmed))
  #   country == "China" |
  #   country == "Italy" |
  #   country == "Thailand"|country == "US" ) %>%
  # dplyr::group_by(country, type) %>%
  # dplyr::summarise(total = sum(cases)) %>%
  # tidyr::pivot_wider(
  #   names_from = type,
  #   values_from = total
  # ) %>%
  # # dplyr::mutate(unrecovered = confirmed - ifelse(is.na(recovered), 0, recovered) - ifelse(is.na(death), 0, death)) %>%
  # dplyr::mutate(unrecovered = confirmed - ifelse(is.na(death), 0, death)) %>%
  # dplyr::arrange(confirmed) %>%
  # dplyr::ungroup() %>%
  # dplyr::mutate(country = dplyr::if_else(country == "United Arab Emirates", "UAE", country)) %>%
  # dplyr::mutate(country = dplyr::if_else(country == "Mainland China", "China", country)) %>%
  # dplyr::mutate(country = dplyr::if_else(country == "North Macedonia", "N.Macedonia", country)) %>%
  # dplyr::mutate(country = trimws(country)) %>%
  # dplyr::mutate(country = factor(country, levels = country))
###growth rate##################
#Estimate the ratio method , this just calculated pop at t+1/pop at t
lambda = df_ind_conf$total_cases[-1]/ df_ind_conf$total_cases[-length(df_ind_conf$total_cases)] #The #"-" notation excludes specified entry of a vector
#lambda
#mean lambda
#mean(lambda, na.rm = T)
#sd(lambda, na.rm = T)
#Mean and sd of continuous time disease growth rate
r = mean(log(lambda), na.rm = T)
sd_r = sd(log(lambda), na.rm = T)


#generate a function that takes a value of r and runs one stochastic simulation
#so we can use both means and variance of r
exp.stoch = function(r_sim) {
  for (i in 1:time) {
    N_sim[i + 1] = N_sim[i] * exp(r_sim[i]) #this is the exponential growth formula
    #N at t+1 = N at t*exp(r*t)
  }
  return(N_sim)
}
time = length(lambda)#how many time steps of data is availble

#sample a value of r for each time step
r_sim = rnorm(time, r, sd_r)
#Initialize the population vector, and use N0 as the starting population size
N_sim = rep(NA, time)
len = length(df_ind_conf$total_cases)-1
#Initialize the population vector, and use N0 as the starting population size
N0 = df_ind_conf$total_cases[1] #To check the model
N_sim[1] = N0

#number of simulations to run
n_sims = 1000 # change it to any number you want...
#Create an empty matrix to hold results
stoch.out = matrix(, nrow = time + 1, ncol = n_sims)
for (s in 1:n_sims) {
  r_sim = rnorm(time, r, sd_r)
  N = exp.stoch(r_sim)
  stoch.out[, s] = N
}

Projected_Cases = rowMeans(stoch.out)
q95 = apply(stoch.out, 1, quantile, probs = c(.025, 0.975))
lower = (q95[1, ])
upper = (q95[2, ])


stoch.out<-as.data.frame(cbind(Projected_Cases,lower,upper,df_ind_conf$day, df_ind_conf$total_cases))
#####################

plotly::plot_ly(
  data = stoch.out,
  x = ~V4,
  # y = ~unrecovered,
  y = ~ Projected_Cases,
  # text =  ~days ,
  # textposition = 'auto',
  type = "scatter",
  mode='lines',
  name = "Average projected cases"
  #marker = list(color = "cyan")
) %>%
  plotly::add_trace(
    y = ~upper,
    # text =  ~ death,
    # textposition = 'auto',
    type = "scatter",
  mode='lines',
    name = "Upper CI"
  #xlim=c(0,100000),
    #marker = list(color = "purple")
  ) %>%
  plotly::add_trace(
    y = ~lower,
    # text =  ~ death,
    # textposition = 'auto',
    name = "Lower CI",
    type = "scatter",
  mode='lines'
   # marker = list(color = "purple")
  ) %>%
  plotly::add_trace(
    y = ~V5,
    type = "scatter",
  mode= "points",
    # text =  ~ death,
    # textposition = 'auto',
    name = "Observed cases"
   #marker = list(color = "purple")
  )
  
```



SIR
=======================================================================




```{r}
#   india
r0= 5*r+1

Infected <- df_ind_conf$confirmed
Day <- 1:(nrow(df_ind_conf))
N <- 1378131607#66000000 # pupulation of the UK


 
# old <- par(mfrow = c(1, 2))
# plot(Day, Infected, type ="b",col='red')
# plot(Day, Infected, log = "y",col='purple')
# abline(lm(log10(Infected) ~ Day))
# title("Confirmed infections COVID-19 in the India", outer = TRUE, line = -2)
#  
SIR <- function(time, state, parameters) {
  par <- as.list(c(state, parameters))
  with(par, {
    dS <- -beta/N * I * S
    dI <- beta/N * I * S - gamma * I
    dR <- gamma * I
    list(c(dS, dI, dR))
    })
}

library(deSolve)
init <- c(S = N-Infected[1], I = Infected[1], R = 0)
sir <- function(parameters) {
  names(parameters) <- c("beta", "gamma")
  out <- ode(y = init, times = Day, func = SIR, parms = parameters)
  fit <- out[ , 3]
  sum((Infected - fit)^2)
}
  
Opt <- optim(c(0.5, 0.5), sir, method = "L-BFGS-B", lower = c(0, 0), upper = c(1, 1)) # optimize with some sensible conditions
#Opt$message
## [1] "CONVERGENCE: REL_REDUCTION_OF_F <= FACTR*EPSMCH"
  
Opt_par <- setNames(Opt$par, c("beta", "gamma"))
#print(Opt_par)
##      beta     gamma 
## 0.6746089 0.3253912
  
R0= Opt$par[1]/Opt$par[2]

t <- 1:150 # time in days
fit <- data.frame(ode(y = init, times = t, func = SIR, parms = Opt_par))
#col <- 1:3 # colour
# print(fit) 
# 
# plotly::plot_ly(
#   data = fit,
#   x = ~t,
#   # y = ~unrecovered,
#   y = ~ log(fit[,3]),
#   # text =  ~days ,
#   # textposition = 'auto',
#   type = "scatter",
#   mode='lines',
#   name = "Infected")
# # yaxis = list(type = "log")) %>%
#   #marker = list(color = "cyan")
# 
#   plotly::add_trace(
#     y = ~ fit[,4],
#     # text =  ~ death,
#     # textposition = 'auto',
#     type = "scatter",
#     yaxis = list(type = "log"),
#   mode='lines',
#     name = "Recovered"
#   #xlim=c(0,100000),
#     #marker = list(color = "purple")
#   )
```
Row {data-width=200}
-----------------------------------------------------------------------

### confirmed {.value-box}
```{r}

valueBox(
  value = format(R0),
  caption = "Reproductive rate",
  #icon = "fas fa-user-md",
  color = confirmed_color
)
```


Row 
-----------------------------------------------------------------------

### **Daily infections** 
    
```{r}
matplot(fit$time, fit[ , 3], type = "l", xlab = "Day", ylab = "Number of cases", lwd = 2, lty = 1, col = c("orange")) #log = "y")
 
points(Day, Infected,col='green')
legend("topright", c( "Infected"), lty = 1, lwd = 2, col =c("orange"), inset = 0.05)
title("Predicted Cases India", outer = TRUE, line = -2)

```





Map
=======================================================================

### **World map of cases** (*use + and - icons to zoom in/out*)

```{r}
# map tab added by Art Steinmetz
library(leaflet)
library(leafpop)
library(purrr)
cv_data_for_plot <- coronavirus %>%
  # dplyr::filter(country == "India") %>%
  dplyr::filter(cases > 0) %>%
  dplyr::group_by(country, province, lat, long, type) %>%
  dplyr::summarise(cases = sum(cases)) %>%
  dplyr::mutate(log_cases = 2 * log(cases)) %>%
  dplyr::ungroup()
cv_data_for_plot.split <- cv_data_for_plot %>% split(cv_data_for_plot$type)
pal <- colorFactor(c("green", "orange", "pink"), domain = c("confirmed", "death", "recovered"))
map_object<- leaflet() %>% addProviderTiles(providers$OpenStreetMap) 
#map_object <- leaflet() %>% addProviderTiles(providers$Stamen.Toner)
names(cv_data_for_plot.split) %>%
  purrr::walk(function(df) {
    map_object <<- map_object %>%
      addCircleMarkers(
        data = cv_data_for_plot.split[[df]],
        lng = ~long, lat = ~lat,
        #                 label=~as.character(cases),
        color = ~ pal(type),
        stroke = FALSE,
        fillOpacity = 0.4,
        radius = ~log_cases,
        popup = leafpop::popupTable(cv_data_for_plot.split[[df]],
          feature.id = FALSE,
          row.numbers = FALSE,
          zcol = c("type", "cases", "country", "province")
        ),
        group = df,
        #                 clusterOptions = markerClusterOptions(removeOutsideVisibleBounds = F),
        labelOptions = labelOptions(
          noHide = F,
          direction = "auto"
        )
      )
  })

map_object %>%
  addLayersControl(
    overlayGroups = names(cv_data_for_plot.split),
    options = layersControlOptions(collapsed = FALSE)
  )
```





About
=======================================================================

**The Coronavirus Dashboard: the case of India**

This Coronavirus dashboard: the case of India provides an overview of the 2019 Novel Coronavirus COVID-19 (2019-nCoV) epidemic for India. This dashboard is built with R using the R Makrdown framework and was adapted from this [dashboard](https://ramikrispin.github.io/coronavirus_dashboard/){target="_blank"} by Rami Krispin.
Code also modified from
https://www.antoinesoetewey.com/files/coronavirus-dashboard.html
**Code**


**Data**

The input data for this dashboard is the dataset available from the [`{coronavirus}`](https://github.com/RamiKrispin/coronavirus){target="_blank"} R package. Make sure to download the development version of the package to have the latest data:


```
install.packages("devtools")
devtools::install_github("RamiKrispin/coronavirus")
```

The data and dashboard are refreshed on a daily basis.

The raw data is pulled from the Johns Hopkins University Center for Systems Science and Engineering (JHU CCSE) Coronavirus [repository](https://github.com/RamiKrispin/coronavirus-csv){target="_blank"}.