R - Draw cases per 100k population - r

I try to draw line COVID cases for each date. I do not have output, the lecturer gave just questions. I solved the question but my problem is the output. It looks weird. Here is the question:
"For the ten countries with the highest absolute number of total deaths, draw the following line graphs to visualize whether epidemic has started to slow down and how the growth rate of new cases/deaths differs across those countries.
a) Number of new cases at each date (absolute number vs per 100.000 population)"
Here is my codes:
library(utils)
COVID_data <-read.csv("https://opendata.ecdc.europa.eu/covid19/nationalcasedeath_eueea_daily_ei/csv", na.strings = "", fileEncoding = "UTF-8-BOM")
#Finding ten countries where the highest absolute total deaths number is
abs_total_deaths <-COVID_data %>%
group_by(countriesAndTerritories) %>%
summarise(abs_total_deaths = sum(deaths)) %>%
arrange(desc(abs_total_deaths))
abs_ten_total_deaths <- c('Italy','France','Germany','Spain','Poland',
'Romania','Czechia','Hungary','Belgium','Bulgaria')
#Calculate new cases by dividing absolute number to 100.000 population
#Draw line for each country
COVID_data %>%
filter(countriesAndTerritories %in% abs_ten_total_deaths) %>%
filter(cases >0) %>%
mutate(new_cases = cases/100000) %>%
ungroup() %>%
ggplot()+
geom_line(aes(x = dateRep, y = new_cases, color = countriesAndTerritories),size=1)+
labs(x="Date",
y="New Cases",
title="New Cases per 100.000 population") +
facet_wrap(~countriesAndTerritories)+
theme_bw()
I will also add a pic of my output. I think my graph is not correct, because the output looks really weird. I can't understand where I make a mistake. If you help me, I'll be appreciated that.
Here is the output:

Looking at Belgium, I get total deaths = 25051 from your data file, which tallies exactly with the data here.
It's obvious that the highest value (by far) for every country occurs "on" the earliest date for the country in the file. Amongst your top ten (I agree with your selection), this is 01Mar2021 for every country apart from Spain, and 28Feb2021 for Spain.
These two facts lead me to conclude (1) your graphs correctly display the data you have asked them to summarise and that (2) you have a data artefact: the first record for each country contains the cumulative total to date, whereas subsequent dates contain data reported "in the previous 24 hours". I use quotes because different countries have different reporting conventions. For example, in the UK (since August 2020) "COVID-related deaths" are deaths from any cause within 28 days of a positive COVID test. Citation
Therefore, to get meaningful graphs, I think your only option is to discard the cumulative data contained in the first record for each country. Here's how I would do that:
library(utils)
library(tidyverse)
COVID_data <-read.csv("https://opendata.ecdc.europa.eu/covid19/nationalcasedeath_eueea_daily_ei/csv", na.strings = "", fileEncoding = "UTF-8-BOM")
# For better printing
COVID_data <- as_tibble(COVID_data)
# Which countries have the higest absolute death toll?
# [I get the same countries as you do.]
top10 <- COVID_data %>%
group_by(countriesAndTerritories) %>%
summarise(TotalDeaths=sum(deaths)) %>%
slice_max(TotalDeaths, n=10) %>%
distinct(countriesAndTerritories) %>%
pull(countriesAndTerritories)
COVID_data %>%
filter(countriesAndTerritories %in% top10) %>%
mutate(
deathRate=100000 * deaths / popData2020,
caseRate=100000 * cases /popData2020,
Date=lubridate::dmy(dateRep)
) %>%
arrange(countriesAndTerritories, Date) %>%
group_by(countriesAndTerritories) %>%
filter(row_number() > 1) %>%
ggplot() +
geom_line(aes(x=Date, y=deathRate)) +
facet_wrap(~countriesAndTerritories)
The critical part that excludes the first data row for each country is
arrange(countriesAndTerritories, Date) %>%
group_by(countriesAndTerritories) %>%
filter(row_number() > 1) %>%
The call to arrange is necessary because the data are not in date order to begin with.
This gives the following plot
which is much more like what I (and I suspect, you) would expect.
The sawtooth patterns you see are most likely also reporting artefacts: deaths that take place over the weekend (or on public holidays) are not reported until the following Monday (or next working day). This is certainly true in the UK.

Related

how to group and summarise column by two other columns

I have a question like that "For 5 countries of your choice, use a group bar chart to compare “deaths per 100 confirmed cases” in each year since the beginning of the pandemic."
I wrote some code like :
COVID_data%>%
filter(countriesAndTerritories%in%selected_countries)%>%
drop_na(deaths)%>%
filter(deaths>0, cases>0)%>%
mutate(d =(deaths*100)/cases)%>%
ggplot(aes(x=countriesAndTerritories, y=d, fill=as.factor(year)))+
geom_bar(position = "dodge", stat = "identity")+
labs(x="Countries",y="Deaths Per 100 Cases", fill="year")+
ggtitle("Number of Deaths per 100 confirmed cases in each year")
It gives me this output:
but the output of my teacher is like that:
Our output of France and Italy are different I examined my data and calculate the number of deaths per 100 cases and my data looks correct I couldn't find my mistake. Could you help me?
My data is from this link:
https://www.ecdc.europa.eu/en/publications-data/data-daily-new-cases-covid-19-eueea-country
The most obvious problem in the code submitted in the question is that it does not correctly aggregate cases and deaths by country and year. Less obvious errors are related to choices made to subset the data, handling of missing values, and the use of stat = "identity" as an argument in geom_bar().
Here's a completely reproducible example that reproduces the instructor's chart.
First, we load the data from the European CDC.
library(ggplot2)
library(dplyr)
library(tidyr)
data <- read.csv("https://opendata.ecdc.europa.eu/covid19/nationalcasedeath_eueea_daily_ei/csv",
na.strings = "", fileEncoding = "UTF-8-BOM")
Next, we create a list of countries to subset that match those in the instructor's chart.
# select some countries
countryList <- c("France","Italy","Germany","Poland","Romania")
Here we group by country and year, and then aggregate cases & deaths, then we calculate the death rate (deaths per 100 confirmed cases), and save to an output data frame.
data %>%
filter(countriesAndTerritories %in% countryList) %>%
group_by(countriesAndTerritories,year) %>%
summarise(cases = sum(cases,na.rm=TRUE),
deaths = sum(deaths,na.rm=TRUE)) %>%
mutate(deathRate = deaths / (cases / 100)) -> summedData
We use the na.rm = TRUE argument on sum() to include as much of the data as possible, since the codebook tells us that these are daily reports of cases and deaths.
If we view the data frame with View(summedData), we see that the death rates are between 1 and 4, as expected.
Having inspected the data, we plot it with ggplot().
Diagnosing the Errors
We'll walk step-by-step through the code of the original post to find the errors, now that we know we are able to reproduce the professor's chart with the data provided from the European CDC.
After reading the data as above, we subset countries and execute the first part of the dplyr pipeline, and save to a data frame.
selected_countries <- c("France","Italy","Norway","Sweden","Finland")
data%>%
filter(countriesAndTerritories%in%selected_countries) -> step1
In the RStudio object viewer we see that the resulting data frame has 4,240 observations.
If we summarize the data to look at the average daily cases and average daily deaths, we see that the cases average 12260.9 while deaths average 81.03.
> mean(step1$cases,na.rm=TRUE)
[1] 12260.9
> mean(step1$deaths,na.rm=TRUE)
[1] 81.03202
So far, so good because because this means that the average death rate across all the data is less than 1.0, which makes sense given worldwide reports about COVID mortality rates since March 2020.
> mean(step1$deaths,na.rm=TRUE) / (mean(step1$cases,na.rm=TRUE) /100)
[1] 0.6608977
Next, we execute the tidyr::drop_na() function and see what happens.
library(tidyr)
step1 %>% drop_na(deaths) -> step2
nrow(step2)
Looks like we've lost 24 observations.
> nrow(step2)
[1] 4216
When we sort by deaths and inspect the output from step1 in the RStudio data viewer, we find the disappearing observations in Norway. There are 24 days where there were cases recorded but no deaths.
Still, there's nothing to suggest we'd generate a graph where 400 people die for every 100 confirmed COVID cases.
Next, we apply the next operation in the original poster's dplyr pipeline and count the rows.
step2 %>% filter(deaths>0, cases>0) -> step3
nrow(step3)
Hmm... we've lost over 980 rows of data now.
> nrow(step3)
[1] 3231
At this point the code is throwing valid data away, which is going to skew the results. Why? COVID case and death counts are notorious for data corrections over time, so sometimes governments will report negative cases or deaths to correct past over-reporting errors.
Sure enough, our data includes rows with negative values.
> summary(step1$cases)
Min. 1st Qu. Median Mean 3rd Qu. Max. NA's
-348846.0 275.5 1114.0 12260.9 7570.5 501635.0 1
> summary(step1$deaths)
Min. 1st Qu. Median Mean 3rd Qu. Max. NA's
-217.00 1.00 11.00 81.03 76.00 2004.00 24
>
Wow! one country reported -348,846 cases in one day. That's a major correction.
Inspecting the data again, we see that France is the culprit here. If we were conducting a more serious analysis with this data, the researcher would be obligated to assess the validity of this observation by doing things as reviewing news reports about case COVID reporting corrections in France during 2021.
Now, when the original code uses mutate() to calculate death rates, it does not aggregate by countriesAndTerritories or year.
step3 %>% mutate(d =(deaths*100)/cases) -> step4
Therefore, when the code uses ggplot() with geom(stat = "identity") the y axis uses the values of the individual observations, 3,231 at this point, and produces unexpected results.
Corrected Version of Original Poster's Chart
Here is the code that correctly analyzes the data, using the five countries selected by the original poster.
countryList <- c("France","Italy","Norway","Sweeden","Finland")
data %>%
filter(countriesAndTerritories %in% countryList) %>%
group_by(countriesAndTerritories,year) %>%
summarise(cases = sum(cases,na.rm=TRUE),
deaths = sum(deaths,na.rm=TRUE)) %>%
mutate(deathRate = deaths / (cases / 100)) -> summedData
# plot the results
ggplot(data = summedData,
aes(x=countriesAndTerritories, y=deathRate, fill=as.factor(year)))+
geom_bar(position = "dodge", stat = "identity")+
labs(x="Countries",y="Deaths Per 100 Cases", fill="year")+
ggtitle("Number of Deaths per 100 confirmed cases in each year")
...and the output, which has death rates between 1 and 3.5%.
Note that the data frame used to generate the chart has only 12 observations, or one observation per number on the chart. This is why stat = "identity" can be used with geom_bar(). ggplot() uses the value of deathRate to plot the height of each bar along the y axis.
Conclusions
First, it's important to understand the details of the data we're analyzing, especially when there are plenty of outside references such as worldwide COVID death rates.
Second, it's important to understand what are valid observations in a data set, such as whether it's reasonable for a data correction like the one France made in May 2021.
Finally, it's important to conduct a face validity analysis of the results. Is it realistic to expect 400 people to die for every 100 confirmed COVID cases? For a disease with a worldwide deaths reported between 1 and 4% of confirmed cases, probably not.

Smoothing out missing values in R dataframe

I am using the dataset - https://data.ca.gov/dataset/covid-19-cases/resource/7e477adb-d7ab-4d4b-a198-dc4c6dc634c9 to look into covid cases and deaths in California.
As well as looking at cases/deaths by ethnicity I have grouped the data to give a total column of cases deaths per day. I also used the lag function to give a daily case / death amount.
However on 2 days in December (23rd and 30th) no increment to the cases or deaths columns were made so the daily cases and deaths read 0. The following day the data is 'caught up' with an extra large amount being added on, clearly the sum of the 2 days. (I suspect Christmas and New Year are the causes)
Is there a way of fixing this data? e.g. splitting the double days measurement into half and populating the cells with this, and then retrospectively altering the daily cases and daily deaths figures?
Hopefully the screenshots will clarify what i mean.
Here is the code I have used:
demog_eth <- (read.csv ("./Data/case_demographics_ethnicity.csv", header = T, sep = ","))
demog_eth$date <-as.Date(demog_eth$date)
#Create a DF with total daily information
total_stats <- data.frame(demog_eth$cases,demog_eth$deaths,demog_eth$date)
names(total_stats) <- c('cases', 'deaths', 'date')
total_stats <- total_stats %>% group_by(date) %>% summarise(cases = sum(cases), deaths = sum(deaths))
#Add daily cases and deaths by computing faily difference in totals
##Comment - use lag to look at previous rows
total_stats <- total_stats %>%
mutate(daily_cases = cases-lag(cases),
daily_deaths = deaths-lag(deaths))
The top paragraph of text in the image says cases and deaths. It should say Daily Cases and Daily Deaths. Apologies
df <- data.frame(col=seq(1:100), col2=seq(from=1, to=200, by=2))
df[c(33, 2),] <- 0
zeros <- as.integer(rownames(df[df$col == 0,])) # detect rows with 0
for (i in zeros){
df[i,"col"] <- 0.5 * df[i+1,"col"]
df[i+1,"col"] <- 0.5 * df[i+1,"col"]
}
Sorry, that I used own simple example data. But the mechanism should work if adapted.

Data Aggregation Using For Loops

I have a data set that has individual basketball players statistics for each team for 17 years. In R I am trying to turn these player level observations into team level observations (for each year) by using a for loop which iterates through year and team and then aggregates the top three scorer's individual statistics (points, assists, rebounds etc). How would you recommend I proceed? (below you will find my current attempt, it only pulls the observations from the last teams and year of the data set and can't pull other statistics such as assists and rebound numbers from the 3 top scorers).
for (year in 2000:2017) {
for (team in teams) {
ts3_points =top_n(select(filter(bball, Tm == team & Year == year), PPG),3)
}
}
Would be more helpful with your data but I don't think you will need to have two for loops. Just need to use dplyr. Below I used some dumby data to try to recreate your issue...
colname key:
month == years
carrier == team
origin == player
library(dplyr)
library(nycflights13) # library with dumby data
flights %>%
group_by(month, carrier, origin) %>%
summarise(hour_avg = mean(hour)) %>% # create your summary stats
arrange(desc(hour_avg)) %>% #sort or data by a summary stat
top_n(n = 3) # return highest hour_avg
# returns the highest hour_avg origin (player) for every month and carrier (year and team)
Hope this helps!

How do i summarize values attributed to several variables in a data set?

First of all I have to describe my data set. It has three columns, where number 1 is country, number 2 is date (%Y-%m-%d), and number 3 is a value associated with each row (average hotel room prices). It continues like that in rows from 1990 to 2019. It works as such:
Country Date Value
France 2011-01-01 700
etc.
I'm trying to turn the date into years instead of the normal %Y-%m-%d format, so it will instead sum the average values for each country each year (instead of each month). How would I go about doing that?
I thought about summarizing the values totally for each country each year, but that is hugely tedious and takes a long time (plus the code will look horrible). So I'm wondering if there is a better solution for this problem that I'm not seeing.
Here is the task at hand so far. My dataset priceOnly shows the average price for each month. I have also attributed it to show only values not equal to 0.
diffyear <- priceOnly %>%
group_by(Country, Date) %>%
summarize(averagePrice = mean(Value[which(Value!=0.0)]))
You can use the lubridate package to extract years and then summarise accordingly.
Something like this:
diffyear <- priceOnly %>%
mutate(Year = year(Date)) %>%
filter(Value > 0) %>%
group_by(Country, Year) %>%
summarize(averagePrice = mean(Value, na.rm = TRUE))
And in general, you should always provide a minimal reproducible example with your questions.

How to convert date to lunar date in R?

I have fisheries data set ( sample data set) . I'm going to study moons impact on the fish catch. I used lunar package to find moon phase of each fishing day.
library(lunar)
data$lunar_phase <- lunar.phase(as.Date(data$fdate))
output as follows
fdate lunar_phase
29/3/2006 3.51789248
28/3/2006 1.255536876
24/3/2006 4.559716361
26/3/2006 2.801242263
25/3/2006 0.538886659
lunar package can be used to categorize lunar phase into 4 or 8 periods.
I need to convert the fishing date to relative lunar cycle date. Lunar cycle is 29.53 days. If lunar day 0 = full moon, then find lunar cycle dates of other dates.
Is there any possible way to do that?
Expected output may be as follows
fdate lunar_day
29/3/2006 6
28/3/2006 4
24/3/2006 10
26/3/2006 5
25/3/2006 1
I don't know of a package that calculates "lunar day" from a date. In theory you could do it from your dataset, by identifying the maximum and minimum values for phase, then converting phases to percentages and rounding up as a proportion of 29.53.
However, the lunar package also calculates illumination (as a fraction of visible surface). I think this is a good proxy for lunar day and also gives you a physical value, rather than something more arbitrary.
Using your data, it's clear that new moon occurs near the start of the month:
library(tidyverse)
library(lunar)
sample_data <- read_csv("sample_data.csv")
sample_data %>%
mutate(Date = as.Date(fdate, "%d/%m/%Y"),
illum = lunar.illumination.mean(Date)) %>%
ggplot(aes(Date, illum)) + geom_point()
We could also fill in the missing dates, which makes the lunar cycle apparent:
all_dates <- data.frame(Date = seq.Date(min(as.Date(sample_data$fdate, "%d/%m/%Y")),
max(as.Date(sample_data$fdate, "%d/%m/%Y")),
by = "1 day")) %>%
mutate(illum = lunar.illumination.mean(Date))
all_dates %>%
ggplot(aes(Date, illum)) + geom_point()
Now, assuming your dataset has a column named catch, we could begin analysis by joining the catch data with the full date range, then plotting catch and lunar illumination. This dataset may also be used for regression, correlation etc.
# simulated catch data
set.seed(123)
sample_data <- sample_data %>%
mutate(catch = rnorm(16, 100, 30))
all_dates %>%
left_join(mutate(sample_data, Date = as.Date(fdate, "%d/%m/%Y"))) %>%
select(Date, illum, catch) %>%
gather(variable, value, -Date) %>%
ggplot(aes(Date, value)) +
geom_point() +
facet_grid(variable~., scales = "free_y")
For each subsequent day from new moon until full moon and the vice versa, the lunar phase increases by 0.212769. So when you run the code below, you get an approximated lunar day :
library(lunar)
lunar_day <- lunar.phase(as.Date("2020-07-21")) /(0.212769)
round(lunar_day, 0)
This works fine , approximately, to 29 days and starting again with new moon. A tidyverse code is given below:
library(lunar)
library(tidyverse)
new_data <-
data %>%
mutate(lunar_day = lunar.phase(as.Date(fdate)) / 0.212769) %>%
mutate_if(is.numeric(lunar_day),round, 0)
Post 14th day, it is the cycle from full-moon to new moon. A function can be written where the cycle can be represented as {new, wax-1, wax-2,...., full, wane-1, wane-2,...., new}.

Resources