【问题标题】:How to remove the day from the date and leave only the month and year from a column in a large dataset in r markdown?如何从日期中删除日期并仅从 r markdown 中的大型数据集中的列中保留月份和年份?
【发布时间】:2020-04-27 18:34:05
【问题描述】:

我有一个大型数据集,其中一列包含格式为 DD/MM/YYYY 的日期,我希望只有 MM/YYYY。有没有办法将此应用于数据集dat$date 中的整个列?

【问题讨论】:

    标签: r


    【解决方案1】:

    我们可以先用as.Date转换成Date类,然后再用format

    dat$date <- format(as.Date(dat$date, "%d/%m/%Y"), "%m/%Y")
    

    或者另一种选择是正则表达式来匹配字符串开头 (^) 后跟 / 的数字 (\\d+) 并替换为空白 ('')

    dat$date <- sub("^\\d+\\/", "", dat$date)
    

    数据

    dat <- data.frame(date = c('05/10/2015', '15/05/2010'), stringsAsFactors = FALSE)
    

    【讨论】:

    • 第二个选项效果更好,但它给了我一天而不是一个月有没有办法代替月份?
    • @MCM 你说格式是 DD/MM/YYYY 所以它正在删除 DD/
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-02
    • 1970-01-01
    • 2020-01-08
    • 2016-02-10
    • 2017-06-13
    相关资源
    最近更新 更多