Spatial Digger
Spatial Digger

Reputation: 1993

rbind adding a row with a date value in it

I'm trying to add a new row to this dataframe, I can add data using rbind() but the date is replaced with NA where am I going wrong?

library(httr)
library(dplyr)
library(ggplot2)
library(gghighlight)
library(zoo)
library(lubridate)

GET("https://opendata.ecdc.europa.eu/covid19/casedistribution/csv", authenticate(":", ":", type="ntlm"), write_disk(tf <- tempfile(fileext = ".csv")))
data <- read.csv(tf)

lab_notes <- paste0("Data as provided by European Centre for Disease Prevention and Control", "and Engineering (JHU CSSE) and obtained daily.")

#data.today<- c(NaN,06,06,2020,0,357,"United_Kingdom", "UK", "GBR",0,"Europe")
#data <- rbind(data, data.today)
#data$dateRep[c(21548)] <- as.factor(c("06/06/2020"))
#data$dateRep[is.na(data$dateRep)] <- as.factor("06/06/2020")

data$geoId <- as.character(data$geoId)
data$dateRep <- as.character(data$dateRep)
data$dateRep <- as.Date(data$dateRep, "%d/%m/%Y")

#data$dateRep[c(21548)] <- today() + days(1)

# Countries you are interested in plotting

geo_ids <- c("UK") 

# selecting data after peak, April the 8th
data.uk <- subset(data, geoId == "UK") %>% arrange(dateRep) ```

Upvotes: 0

Views: 350

Answers (1)

starja
starja

Reputation: 10365

The problem is that you data column was not in a date format, but a factor which internally is an integer, and this interpretation as date leads to problems. To get character columns and not factor when reading in data, set stringsAsFactors = FALSE in read.csv. Then you can convert dateRep to a date format and add a row. I formatted the extra row as a data.frame, so you already have the correct column types.

library(httr)
library(lubridate)
GET("https://opendata.ecdc.europa.eu/covid19/casedistribution/csv", authenticate(":", ":", type="ntlm"), write_disk(tf <- tempfile(fileext = ".csv")))
data <- read.csv(tf, stringsAsFactors = FALSE)

data$dateRep <- as.Date(data$dateRep, format = "%d/%m/%Y")

data.today<- data.frame(today(),06,06,2020,0,357,"United_Kingdom", "UK", "GBR",0,"Europe")
colnames(data.today) <- colnames(data)

rbind(data[1, ], data.today)
     dateRep day month year cases deaths countriesAndTerritories geoId countryterritoryCode popData2018 continentExp
1 2020-06-05   5     6 2020   787      6             Afghanistan    AF                  AFG    37172386         Asia
2 2020-06-05   6     6 2020     0    357          United_Kingdom    UK                  GBR           0       Europe

Upvotes: 3

Related Questions