简体   繁体   English

将“Year-ISO Week”字符 object 转换为日期 object

[英]Transform a "Year-ISO Week" character object to a Date object

I've been having some struggles with dates.我一直在与日期作斗争。 Namely, being able recognize a variable (as a Date variable) that has dates registered by the following manner: Year-ISO week.即,能够识别具有通过以下方式注册的日期的变量(作为Date变量):Year-ISO week。 So the following code:所以下面的代码:

class("2021-20")

Idealy should return: Date .理想情况下应该返回: Date

The following code recognizes it as a date , but it returns a date that I don't understand where it comes from.下面的代码将它识别为一个date ,但它返回一个我不明白它来自哪里的日期。 And even if I try with other dates (different values of the ISO week), I always get the same response:即使我尝试使用其他日期(ISO 周的不同值),我也总是得到相同的响应:

as.Date("2021-20", format = "%Y-%W")
[1] "2021-12-13"

I've tried transforming "normal dates" to the format year-iso week, but it leads to no where, I can never get it to be recognized as a Date object, and I need to perform ggplot2 graphs.我试过将“正常日期”转换为 year-iso week 格式,但它导致无处可去,我永远无法将其识别为Date object,我需要执行ggplot2图表。

This question was linked to this one , although the question itself is very similar, I am still not able to get the result I desire. This question was linked to this one ,虽然问题本身非常相似,但我仍然无法得到我想要的结果。

As you noted in the comments, R has a Date format that is always YYYY-MM-DD, so if you want to plot data with a date axis, it often makes sense to convert your format to that.正如您在评论中指出的那样,R 的日期格式始终为 YYYY-MM-DD,因此如果您希望 plot 数据带有日期轴,将您的格式转换为该格式通常很有意义。 But there's nothing preventing you from subsequently formatting the Date data to display with an arbitrary other format.但是没有什么可以阻止您随后格式化 Date 数据以使用任意其他格式显示。 This will change the display appearance on the axis after the physical position mapping has occurred using the Date data.这将在使用日期数据发生物理 position 映射后更改轴上的显示外观。

So you can plot year-week data, but you have to take a detour to Date and then come back.所以你可以plot年周数据,但是你得绕个Date再回来。 As noted in related questions, year-weeks include 7 days, so to convert a year-week to a Date you need to specify which day of the week to use;如相关问题所述,年-周包括 7 天,因此要将年-周转换为日期,您需要指定使用一周中的哪一天; that's the "1" in the paste part.那就是粘贴部分中的“1”。

In the example data below, I've added gaps so you can see how the Date data is mapped correctly to the timeline.在下面的示例数据中,我添加了间隙,以便您可以看到日期数据如何正确映射到时间轴。

data.frame(year = c(rep(2021,8), rep(2022, 3)),
           week = c(45:52, 1, 3, 5),
           val = 1:11) |>

  ggplot(aes(x = as.Date(paste(year, week, 1, sep = "-"), "%Y-%W-%w"),
             y = val)) +
  geom_point() +
  scale_x_date(date_breaks = "week", date_labels = "%Y-%W", name = "year-week")

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM