【问题标题】:How can I change a date style in R?如何更改 R 中的日期样式?
【发布时间】:2022-08-13 21:44:02
【问题描述】:

我的数据集中的一列包括月份名称和年份等日期。我想将月份的名称更改为数字。

我的数据集如下所示:

我想将 ldr_start 列更改为: ldr_start 3/92 7/93 8/93

谢谢你。

    标签: r


    【解决方案1】:

    无论哪种情况,这都不是真正的“约会”。 zoo 包确实定义了一个 yearmon 类。在这里,我们可以只使用 strsplit 并处理月份字符,匹配 R 常量 month.abb,然后重新加入:

    dat <- scan(text="Mar-92,Feb-93,Jul-94,Sep-95", what = "", sep=",")
    #Read 4 items
    datspl <- strsplit(dat, split="-")
    sapply( datspl, function(mnyr){ paste( match(mnyr[1], month.abb), mnyr[2], sep="/")})
    #[1] "3/92" "2/93" "7/94" "9/95"
    

    【讨论】:

      【解决方案2】:

      我们也可以使用stringrstr_replace_all

      data <- c("Mar-92", "Feb-93", "Jul-94")
      
      str_replace_all(data, setNames(as.character(1:12), month.abb))
      

      输出:

      [1] "3-92" "2-93" "7-94"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-01-11
        • 1970-01-01
        • 1970-01-01
        • 2019-01-09
        • 1970-01-01
        • 1970-01-01
        • 2015-03-03
        相关资源
        最近更新 更多