【问题标题】:How can I convert daily dates to Monthly or to first day of every month [duplicate]如何将每日日期转换为每月或每月的第一天 [重复]
【发布时间】:2020-06-11 11:26:15
【问题描述】:

我正在尝试转换这个大数据集日期列,它是格式 (YYYY/MM/DD),我希望只是将“日期”变量中的任何观察结果转换为相应月份的第一天.(2018/02/03 -> 2018/02/01) 我对数据表很陌生,如果这是一个简单的问题,我深表歉意。 这是我的数据集的示例 dput()。

structure(list(quantity = c(NA_real_, NA_real_, NA_real_, NA_real_, 
 NA_real_, NA_real_), price_mid = c(NA_real_, NA_real_, NA_real_, 
NA_real_, NA_real_, NA_real_), value_mid = c(100, 241.85, 241.85, 
241.85, 241.85, 241.85), currency_price = c("GBP", "GBP", "GBP", 
"GBP", "GBP", "GBP"), currency_value = c("GBP", "GBP", "GBP", 
"GBP", "GBP", "GBP"), date = structure(c(13515L, 13516L, 13517L, 
13518L, 13521L, 13522L), class = "Date")), class = c("data.table", 
 "data.frame"), row.names = c(NA, -6L), .internal.selfref = <pointer: 0x15f28c0>)

如果需要对问题进行任何修改,请告诉我。 谢谢

【问题讨论】:

标签: r date


【解决方案1】:

你可以像这样使用format函数

data$date <- format(data$date,format  = "%Y/%m/1")


> data
   quantity price_mid value_mid currency_price currency_value      date
1:       NA        NA    100.00            GBP            GBP 2007/01/1
2:       NA        NA    241.85            GBP            GBP 2007/01/1
3:       NA        NA    241.85            GBP            GBP 2007/01/1
4:       NA        NA    241.85            GBP            GBP 2007/01/1
5:       NA        NA    241.85            GBP            GBP 2007/01/1
6:       NA        NA    241.85            GBP            GBP 2007/01/1

如果您愿意,可以完全放弃这一天,它可能更具代表性。

data$date <- format(data$date,format  = "%Y/%m")

> data
   quantity price_mid value_mid currency_price currency_value    date
1:       NA        NA    100.00            GBP            GBP 2007/01
2:       NA        NA    241.85            GBP            GBP 2007/01
3:       NA        NA    241.85            GBP            GBP 2007/01
4:       NA        NA    241.85            GBP            GBP 2007/01
5:       NA        NA    241.85            GBP            GBP 2007/01
6:       NA        NA    241.85            GBP            GBP 2007/01

【讨论】:

    猜你喜欢
    • 2023-01-26
    • 2019-07-28
    • 2018-06-06
    • 2021-12-06
    • 2013-09-22
    • 2019-09-04
    • 1970-01-01
    • 2018-08-19
    • 1970-01-01
    相关资源
    最近更新 更多