如何使用 lubridate [重复] 重新格式化日期

问题描述 投票:0回答:0

我想在类型为

date
但格式为
%Y-%m
的数据框中创建一个列。

例如,

# create data frame
df <- tibble::tibble(
  date = lubridate::ymd("2023-01-01","2023-01-02","2023-01-03",
                        "2023-01-04","2023-01-05","2023-01-06","2023-01-07",
                        "2023-01-08","2023-01-09","2023-01-10")
)

# we can see that the date column has type "date"
df
#> # A tibble: 10 x 1
#>    date      
#>    <date>    
#>  1 2023-01-01
#>  2 2023-01-02
#>  3 2023-01-03
#>  4 2023-01-04
#>  5 2023-01-05
#>  6 2023-01-06
#>  7 2023-01-07
#>  8 2023-01-08
#>  9 2023-01-09
#> 10 2023-01-10

# but when I try to reformat it, it becomes type "chr"
df |>
  dplyr::mutate(
    date = format(date, format = '%Y-%m')
  )
#> # A tibble: 10 x 1
#>    date   
#>    <chr>  
#>  1 2023-01
#>  2 2023-01
#>  3 2023-01
#>  4 2023-01
#>  5 2023-01
#>  6 2023-01
#>  7 2023-01
#>  8 2023-01
#>  9 2023-01
#> 10 2023-01

创建于 2023-04-20 与 reprex v2.0.2

r lubridate
© www.soinside.com 2019 - 2024. All rights reserved.