【问题标题】:How to retain month/year from the day/month/year date format using R如何使用 R 从日/月/年日期格式中保留月/年
【发布时间】:2020-01-08 21:44:27
【问题描述】:

有一个包含日期的 excel 文件,格式为日/月/年。我想使用 R 以月/年的形式保留月份和年份。

我尝试过使用如下的“格式”功能:

date = c("2/8/2018","22/11/2018","1/2/2019")
n.date <- format(as.Date(date), "%m/%Y")

它给出:

n.date
[1] "08/0002" "11/0022" "02/0001"

但是,我希望有类似的东西

"8/2018" "11/2018" "2/2019".

请问,我该怎么做。非常感谢任何帮助。

【问题讨论】:

    标签: r date format


    【解决方案1】:

    当您将字符串解析为日期时,您应该在调用as.Date 时使用format 选项,并使用掩码%d/%m/%Y。然后,使用您想要的月份-年份掩码致电format()

    date = c("2/8/2018", "22/11/2018", "1/2/2019")
    n.date <- as.Date(date, format="%d/%m/%Y")
    
    format(n.date, "%m/%Y")
    
    [1] "08/2018" "11/2018" "02/2019"
    

    删除前导零:

    output <- format(n.date, "%m/%Y")
    output <- sub("^0*", "", output)
    output
    
    [1] "8/2018"  "11/2018" "2/2019"
    

    【讨论】:

    • 谢谢! @蒂姆·比格莱森。有没有办法去掉 8 和 2 前面的零?
    【解决方案2】:

    如果您检查as.Date(date),它不会给您正确的日期。所以通常@Tim 的答案是要走的路,但是你也可以在这里使用正则表达式来实现你想要的结果

    sub("\\d+/", "", date)
    #[1] "8/2018"  "11/2018" "2/2019" 
    

    这会删除date中后跟“/”的数字。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多