r - 动态数据框中从字符到日期的列名
问题描述
#我有一个以 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。
希望你们中的一些专家可以帮助我解决这个问题。
解决方案
渴望评论。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
推荐阅读
- google-apps-script - 存储数组以在多个触发器上使用
- centos - cifs 挂载中缺少/不同的文件
- r - 使用 which() 函数 R 两个相同的 R 日期不相等
- google-apps-script - 有没有办法在更多列中获取日期
- javascript - 如何使用 CSS 或 JS 使图像在多个分区上粘贴到所需的长度?
- spartacus-storefront - 用于 ASM 实施参考的 Spartacus SAML 单点登录
- javafx - 在 javafx HtmlEditor 中,java 虚拟键盘输入键不起作用
- ios - AFNetworking 崩溃问题 AFHTTPSessionManager.m ios Objective c
- reactjs - 如何在 Django+React 应用程序中显示外键模型中的特定字段?
- powerbi - 以前所有年份的平均每年