假设我有这个 df(但大得多)
library(lubridate)
df = data.frame(id=1:5,date1 = c("2023/01/02","2023/08/03","2023/09/09","2023/11/05","2023/04/03"),
date2 = c("2023/02/02","2023/09/03","2023/10/09","2023/12/05","2023/05/03"))
我尝试将
lapply
与 dmy
库的 lubridate
功能一起使用,但它不起作用,我不知道为什么。
dd = colnames(df[,-1])
df[dd] = lapply(df[dd],dmy)
输出是
Warning messages:
1: All formats failed to parse. No formats found.
2: All formats failed to parse. No formats found.
我认为你应该使用
ymd
而不是 dmy
,因为你的日期字符串的格式为 %Y/%m/%d
> df %>%
+ mutate_if(is.character, ymd)
id date1 date2
1 1 2023-01-02 2023-02-02
2 2 2023-08-03 2023-09-03
3 3 2023-09-09 2023-10-09
4 4 2023-11-05 2023-12-05
5 5 2023-04-03 2023-05-03
如果你确实想要以
dmy
格式呈现日期,你可以尝试
> df %>%
+ mutate_if(is.character, ~ format(ymd(.x), "%d/%m/%Y"))
id date1 date2
1 1 02/01/2023 02/02/2023
2 2 03/08/2023 03/09/2023
3 3 09/09/2023 09/10/2023
4 4 05/11/2023 05/12/2023
5 5 03/04/2023 03/05/2023