Colnames from characther to date in dynamic dataframe

Viewed 46

#I have a dataframe with colnames as characther. The dataframe is updated every day. #I need to make a timeline graph, and therefore the colnames for the dynamic data collection is in date-format.

#I downloads the df here:

df_death <- read.csv2("https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_global.csv" ,
                        header = TRUE,sep = ",", quote = "\\\"")

#The colnames after [1:4] starts with X1.22.20, i interpret this as month.day.year.

#Before I solve the dates, i format the first four columns into:

df_death$Province.State <- as.factor(jsse_death$Province.State)
df_death$Country.Region <- as.factor(jsse_death$Country.Region)
df_death$Lat <- as.numeric(jsse_death$Lat)
df_death$Long <- as.numeric(jsse_death$Long)

#Then, I filter out the focal country:

df_death_Nor <- jsse_death %>% 
  filter(Country.Region == "Norway")

#convert the colnames into date-format:

names(df_death_Nor)[-1:-4] <- as.Date(names(df_death_Nor)[-1:-4],format="X%M.%d.%y")

#This results in five-digits integers, where first date-column has 18404. #The origin for this (if its a date) date should be 1969-09-02, to receive 2020-01-22, the correct date.

Hope some of you experts could help me with this.

1 Answers

To long for a comment. as.Date() gives us an object of class "Date", which values are actually labelled integers that count the days since "1970-01-01", the so-called "origin". By assigning them to the names, the labels get stripped off. So what you want is to coerce the labels as.character().

names(df_death_Nor)[-1:-4] <- 
  as.character(as.Date(names(df_death_Nor)[-1:-4], format="X%m.%d.%y"))

You probably want to reshape it thereafter?

df_death_Nor_l <- reshape2::melt(df_death_Nor, id.vars=1:4, variable.name="date")
head(df_death_Nor_l, 3)
#   Province.State Country.Region    Lat   Long       date value
# 1                        Norway 60.472 8.4689 2020-01-22     0
# 2                        Norway 60.472 8.4689 2020-01-23     0
# 3                        Norway 60.472 8.4689 2020-01-24     0
tail(df_death_Nor_l, 3)
#     Province.State Country.Region    Lat   Long       date value
# 480                        Norway 60.472 8.4689 2021-05-15   774
# 481                        Norway 60.472 8.4689 2021-05-16   774
# 482                        Norway 60.472 8.4689 2021-05-17   774
Related