分享
三行代码  ›  专栏  ›  技术社区  ›  Rollo99

如何替换R中日期对象中的日期?

  •  2
  • Rollo99  · 技术社区  · 1 周前

    让我们举个例子。

    date = structure(c(10961, 10990, 11018, 11046, 11060, 11088, 11116, 
    11144, 11214, 11235, 11249, 11263, 11305, 11354, 11382, 11423, 
    11452, 11480, 11494, 11508), class = "Date")
    
     [1] "2000-01-05" "2000-02-03" "2000-03-02" "2000-03-30" "2000-04-13" "2000-05-11" "2000-06-08"
     [8] "2000-07-06" "2000-09-14" "2000-10-05" "2000-10-19" "2000-11-02" "2000-12-14" "2001-02-01"
    [15] "2001-03-01" "2001-04-11" "2001-05-10" "2001-06-07" "2001-06-21" "2001-07-05"
    
    

    我想要:

     [1] "2000-01-05" "2000-02-05" "2000-03-05" "2000-03-05" "2000-04-05" "2000-05-05" "2000-06-05"
     [8] "2000-07-05" "2000-09-05" "2000-10-05" "2000-10-05" "2000-11-05" "2000-12-05" "2001-02-05"
    [15] "2001-03-05" "2001-04-05" "2001-05-05" "2001-06-05" "2001-06-05" "2001-07-05"
    
    

    我要做的是:

    
    sub("%d", "05", date, perl = TRUE)
    
    

    pattern 我不知道如何把握这一天。

    有人能帮我吗?

    3 回复  |  直到 1 周前
        1
  •  4
  •   Rui Barradas    1 周前

    date <- as.Date(sub("\\d{2}$", "05", date))
    

    包裹 lubridate :

    lubridate::day(date) <- 5
    
        2
  •  2
  •   Darren Tsai    1 周前

    你可以用 floor_date() 在里面 lubridate

    lubridate::floor_date(date, "month") + 4
    
    #  [1] "2000-01-05" "2000-02-05" "2000-03-05" "2000-03-05" "2000-04-05"
    #  [6] "2000-05-05" "2000-06-05" "2000-07-05" "2000-09-05" "2000-10-05"
    # [11] "2000-10-05" "2000-11-05" "2000-12-05" "2001-02-05" "2001-03-05"
    # [16] "2001-04-05" "2001-05-05" "2001-06-05" "2001-06-05" "2001-07-05"
    
        3
  •  1
  •   Ronak Shah    1 周前

    如果将日期转换为 POSIXlt 对象,您可以更改它的单个组件。

    date <- as.POSIXlt(date)
    date$mday <- 5
    as.Date(date)
    
    # [1] "2000-01-05" "2000-02-05" "2000-03-05" "2000-03-05" "2000-04-05"
    # [6] "2000-05-05" "2000-06-05" "2000-07-05" "2000-09-05" "2000-10-05"
    #[11] "2000-10-05" "2000-11-05" "2000-12-05" "2001-02-05" "2001-03-05"
    #[16] "2001-04-05" "2001-05-05" "2001-06-05" "2001-06-05" "2001-07-05"