gpt4 book ai didi

r - 如何更改为年月周格式?

转载 作者:行者123 更新时间:2023-12-04 11:26:17 24 4
gpt4 key购买 nike

我有年月日格式的日期,我想转换为年月周格式,如下所示:

date            dateweek
2015-02-18 -> 2015-02-8
2015-02-19 -> 2015-02-8
2015-02-20 -> ....
2015-02-21
2015-02-22
2015-02-23
2015-02-24 ...
2015-02-25 -> 2015-02-9
2015-02-26 -> 2015-02-9
2015-02-27 -> 2015-02-9

我试过
data$dateweek <- week(as.POSIXlt(data$date))

但这仅返回没有相应年份和月份的几周。

我也试过:
data$dateweek <- as.POSIXct('2015-02-18')
data$dateweek <- format(data$dateweek, '%Y-%m-%U')
# data$dateweek <- format(as.POSIXct(data$date), '%Y-%m-%U')

但相应的列看起来很奇怪:
date         datetime
2015-01-01 2015-01-00
2015-01-02 2015-01-00
2015-01-03 2015-01-00
2015-01-04 2015-01-01
2015-01-05 2015-01-01
2015-01-06 2015-01-01
2015-01-07 2015-01-01
2015-01-08 2015-01-01
2015-01-09 2015-01-01
2015-01-10 2015-01-01
2015-01-11 2015-01-02

最佳答案

您需要使用 '%Y-%m-%V格式来改变它:

mydate <- as.POSIXct('2015-02-18')

> format(mydate, '%Y-%m-%V')
[1] "2015-02-08"
来自文档 strptime :

%V

Week of the year as decimal number (00–53) as defined in ISO 8601. If the week (starting on Monday) containing 1 January has four or more days in the new year, then it is considered week 1. Otherwise, it is the last week of the previous year, and the next week is week 1. (Accepted but ignored on input.)


还有(美国公约):

%U

Week of the year as decimal number (00–53) using Sunday as the first day 1 of the week (and typically with the first Sunday of the year as day 1 of week 1). The US convention.


这实际上取决于您想为您的案例使用哪一种。
mydate <- as.POSIXct('2015-02-18')

> format(mydate, '%Y-%m-%U')
[1] "2015-02-07"
在你的情况下,你应该这样做:
data$dateweek <- format(as.POSIXct(data$date), '%Y-%m-%U')

关于r - 如何更改为年月周格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30141948/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com