【问题标题】:Convert integer data into year and month [duplicate]将整数数据转换为年和月[重复]
【发布时间】:2020-06-14 13:04:44
【问题描述】:

我有这样的整数数据示例

201901, 201912, 202004

如何使用 R 编程将我的数据转换为年和月。我需要这样的输出:

2019-01, 2019-12, 2020-04

Jan-2019, Dec-2019, Apr-2020

提前谢谢你。

【问题讨论】:

    标签: r date


    【解决方案1】:

    您可以转换为日期,然后使用format

    x <- c(201901, 201912, 202004)
    
    format(as.Date(paste(x, '01'), '%Y%m%d'), '%b-%Y')
    #[1] "Jan-2019" "Dec-2019" "Apr-2020"
    format(as.Date(paste(x, '01'), '%Y%m%d'), '%Y-%m')
    #[1] "2019-01" "2019-12" "2020-04"
    

    你也可以使用zooyearmon

    zoo::as.yearmon(as.character(x), '%Y%m')
    

    使用正则表达式,我们可以捕获 4 和 2 个字符,并在其间插入“-”。

    sub('(.{4})(.{2})', '\\1-\\2', x)
    

    【讨论】:

      猜你喜欢
      • 2021-04-18
      • 2013-11-07
      • 1970-01-01
      • 2019-03-01
      • 2019-07-19
      • 1970-01-01
      • 2013-03-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多