首页 > 解决方案 > 动态数据框中从字符到日期的列名

问题描述

#我有一个以 colnames 为字符的数据框。数据框每天更新。#我需要制作一个时间线图,因此动态数据收集的列名是日期格式的。

#我在这里下载df:

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 = "\\\"")

#[1:4] 之后的列名以 X1.22.20 开头,我将其解释为月.日.年。

#在我解决日期之前,我将前四列格式化为:

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)

#然后,我过滤掉焦点国家:

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

#convert colnames 成日期格式:

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

#这会产生五位整数,其中第一个日期列有 18404。 #这个(如果是日期)日期的原点应该是 1969-09-02,以接收正确的日期 2020-01-22。

希望你们中的一些专家可以帮助我解决这个问题。

标签: rdataframedateconverters

解决方案


渴望评论。as.Date()给了我们一个类的对象"Date",它的值实际上是被标记的整数,计算自 以来的天数"1970-01-01",即所谓的“原点”。通过将它们分配给名称,标签被剥离。所以你想要的是强制标签as.character()

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

之后你可能想重塑它?

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

推荐阅读