【问题标题】:format a date value in R to a string using the format function [duplicate]使用格式函数将 R 中的日期值格式化为字符串
【发布时间】:2021-07-16 06:37:07
【问题描述】:

我在 R 的数据框中有一个日期列,其通常格式为 yyyy-mm-dd,我正在尝试使用格式函数转换为字符串

这是我目前所拥有的

format(data_future$date, '%d/%m/%Y ')

但我得到这样的值 "04/03/2021"

如何从日期和月份中删除前导 0,以便最终结果如下所示

"4/3/2021"

感谢您的帮助

【问题讨论】:

    标签: r


    【解决方案1】:

    您可以编写自己的自定义格式函数-

    custom_format <- function(x1, format, ...) {
      gsub("0(?=\\d/)", "",format(x1, format, ...), perl = TRUE)  
    }
    
    custom_format(as.Date('2021-04-03') + 1:10, '%d/%m/%Y')
    
    # [1] "4/4/2021"  "5/4/2021"  "6/4/2021"  "7/4/2021"  "8/4/2021"  "9/4/2021" 
    # [7] "10/4/2021" "11/4/2021" "12/4/2021" "13/4/2021"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-15
      • 2017-04-09
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      • 2022-07-04
      • 1970-01-01
      • 2018-06-01
      相关资源
      最近更新 更多