将列中的日期和时间转换为 R 中字符中的星期
Converting date with time in a column to week in character in R
我有包含时间的日期信息的数据,我想将它们转换为字符格式的 year
的 week
。例如对于以下数据
Case Time
1 2020-01-12 11:28:46
2 2020-01-22 10:17:24
我想要一个包含值的列,例如 January 6th, 2020
而不是 2020-w02
可以由 date2week
包生成。因此,对于此数据,最喜欢的结果如下:
Case Time time_by_day2week favorite_time
1 2020-01-12 11:28:46 2020-w02 January 6th, 2020
2 2020-01-22 10:17:24 2020-w04 January 20th, 2020
因此,favorite_time 列提到了那一周的 first day (Monday)
。
如果有人能提供帮助,我们将不胜感激。
非常感谢!
我们可以用 floor_date
对 Date
对象进行下限,然后使用 format
library(dplyr)
library(lubridate)
df1 %>%
mutate(Time = as.POSIXct(Time),
favorite_time = format(floor_date(Time, "weeks",
week_start = 1), "%B %dth, %Y"))
# Case Time favorite_time
#1 1 2020-01-12 11:28:46 January 06th, 2020
#2 2 2020-01-22 10:17:24 January 20th, 2020
数据
df1 <- structure(list(Case = 1:2, Time = c("2020-01-12 11:28:46",
"2020-01-22 10:17:24"
)), class = "data.frame", row.names = c(NA, -2L))
我有包含时间的日期信息的数据,我想将它们转换为字符格式的 year
的 week
。例如对于以下数据
Case Time
1 2020-01-12 11:28:46
2 2020-01-22 10:17:24
我想要一个包含值的列,例如 January 6th, 2020
而不是 2020-w02
可以由 date2week
包生成。因此,对于此数据,最喜欢的结果如下:
Case Time time_by_day2week favorite_time
1 2020-01-12 11:28:46 2020-w02 January 6th, 2020
2 2020-01-22 10:17:24 2020-w04 January 20th, 2020
因此,favorite_time 列提到了那一周的 first day (Monday)
。
如果有人能提供帮助,我们将不胜感激。
非常感谢!
我们可以用 floor_date
对 Date
对象进行下限,然后使用 format
library(dplyr)
library(lubridate)
df1 %>%
mutate(Time = as.POSIXct(Time),
favorite_time = format(floor_date(Time, "weeks",
week_start = 1), "%B %dth, %Y"))
# Case Time favorite_time
#1 1 2020-01-12 11:28:46 January 06th, 2020
#2 2 2020-01-22 10:17:24 January 20th, 2020
数据
df1 <- structure(list(Case = 1:2, Time = c("2020-01-12 11:28:46",
"2020-01-22 10:17:24"
)), class = "data.frame", row.names = c(NA, -2L))