对于 strptime 中的 ISO 8601 定义,一周从 2 点钟开始
The week starts at 2 o'clock for the ISO 8601 definition in strptime
使用这个虚拟数据框:
library(tibble)
library(dplyr)
tibble(Date = as.POSIXct(c(1601848800, 1601852400, 1601856000,
1601859600, 1601863200), origin = "1970-01-01")) %>%
mutate(ISOweek = format(as.Date(.$Date), "%V"))
这个结果让我很困惑:
Date ISOweek
<dttm> <chr>
1 2020-10-05 00:00:00 40
2 2020-10-05 01:00:00 40
3 2020-10-05 02:00:00 41
4 2020-10-05 03:00:00 41
5 2020-10-05 04:00:00 41
我正在从 csv 文件中获取 Date 变量,所以我可能以不正确的方式从字符转换为 POSIXct。
as.POSIXct
使用您当地的时区,as.Date
使用 UTC 时区。如果您在 as.POSIXct
中指定时区,您将清楚输出。另外添加日期列应该有助于阐明结果。
library(dplyr)
tibble(Date = as.POSIXct(c(1601848800, 1601852400, 1601856000, 1601859600,
1601863200), origin = "1970-01-01", tz = 'UTC')) %>%
mutate(date = as.Date(Date),
ISOweek = format(date, "%V"))
# Date date ISOweek
# <dttm> <date> <chr>
#1 2020-10-04 22:00:00 2020-10-04 40
#2 2020-10-04 23:00:00 2020-10-04 40
#3 2020-10-05 00:00:00 2020-10-05 41
#4 2020-10-05 01:00:00 2020-10-05 41
#5 2020-10-05 02:00:00 2020-10-05 41
使用这个虚拟数据框:
library(tibble)
library(dplyr)
tibble(Date = as.POSIXct(c(1601848800, 1601852400, 1601856000,
1601859600, 1601863200), origin = "1970-01-01")) %>%
mutate(ISOweek = format(as.Date(.$Date), "%V"))
这个结果让我很困惑:
Date ISOweek
<dttm> <chr>
1 2020-10-05 00:00:00 40
2 2020-10-05 01:00:00 40
3 2020-10-05 02:00:00 41
4 2020-10-05 03:00:00 41
5 2020-10-05 04:00:00 41
我正在从 csv 文件中获取 Date 变量,所以我可能以不正确的方式从字符转换为 POSIXct。
as.POSIXct
使用您当地的时区,as.Date
使用 UTC 时区。如果您在 as.POSIXct
中指定时区,您将清楚输出。另外添加日期列应该有助于阐明结果。
library(dplyr)
tibble(Date = as.POSIXct(c(1601848800, 1601852400, 1601856000, 1601859600,
1601863200), origin = "1970-01-01", tz = 'UTC')) %>%
mutate(date = as.Date(Date),
ISOweek = format(date, "%V"))
# Date date ISOweek
# <dttm> <date> <chr>
#1 2020-10-04 22:00:00 2020-10-04 40
#2 2020-10-04 23:00:00 2020-10-04 40
#3 2020-10-05 00:00:00 2020-10-05 41
#4 2020-10-05 01:00:00 2020-10-05 41
#5 2020-10-05 02:00:00 2020-10-05 41