gpt4 book ai didi

r - 无法在 R 中设置天数和天名(日期始终为字符)

转载 作者:行者123 更新时间:2023-12-04 12:31:09 25 4
gpt4 key购买 nike

要重现的样本数据

a=structure(list(date = c("01.01.2021", "02.01.2021", "03.01.2021", 
"04.01.2021", "05.01.2021", "06.01.2021", "07.01.2021", "08.01.2021",
"09.01.2021", "10.01.2021", "11.01.2021", "12.01.2021", "13.01.2021",
"14.01.2021", "15.01.2021", "16.01.2021", "17.01.2021", "18.01.2021",
"19.01.2021", "20.01.2021"), sales_count = c(10L, 4L, 8L, 6L,
4L, 4L, 4L, 3L, 1L, 5L, 2L, 10L, 5L, 9L, 2L, 8L, 5L, 6L, 8L,
3L)), class = "data.frame", row.names = c(NA, -20L))

为什么我加载数据时,日期是字符?我得到了错误。我的尝试

a$date = as.Date (a$date)lError in charToDate (x):character string is not in a standard unambiguous format

Error in charToDate (x):
character string is not in a standard unambiguous format

我在 SO 中看到许多类似的帖子,但这些解决方案对我没有帮助。如何修复这个错误,那个日期是

date     : Date, format: "2021-01-20" ...

然后如何为每个日期分配日期名称和天数?例如,确实是我想要的输出

sales_count date    day_num weekday
8 2021-01-20 3 Wednesday

谢谢。

最佳答案

您可以使用以下解决方案:

library(dplyr)

a %>%
mutate(date = as.Date(date, "%d.%m.%Y"),
weekday = weekdays(date))

date sales_count weekday
1 2021-01-01 10 Friday
2 2021-01-02 4 Saturday
3 2021-01-03 8 Sunday
4 2021-01-04 6 Monday
5 2021-01-05 4 Tuesday
6 2021-01-06 4 Wednesday
7 2021-01-07 4 Thursday
8 2021-01-08 3 Friday
9 2021-01-09 1 Saturday
10 2021-01-10 5 Sunday
11 2021-01-11 2 Monday
12 2021-01-12 10 Tuesday
13 2021-01-13 5 Wednesday
14 2021-01-14 9 Thursday
15 2021-01-15 2 Friday
16 2021-01-16 8 Saturday
17 2021-01-17 5 Sunday
18 2021-01-18 6 Monday
19 2021-01-19 8 Tuesday
20 2021-01-20 3 Wednesday

或者我们可以使用 lubridate 包。我们应该将等同于base::weekdayswday 函数的label 参数设置为TRUE,否则它返回从周日开始的工作日数:

library(lubridate)

a %>%
mutate(date = dmy(date),
weekday = wday(date, label = TRUE))

关于r - 无法在 R 中设置天数和天名(日期始终为字符),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69014164/

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