在R中将日期格式化为年月 [英] Format Date to Year-Month in R

查看:242
本文介绍了在R中将日期格式化为年月的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将年月格式的当前日期列保留为日期.目前,它已转换为chr格式.我尝试了as_datetime,但将所有值强制为NA. 我正在寻找的格式是:"2017-01"

I would like to retain my current date column in year-month format as date. It currently gets converted to chr format. I have tried as_datetime but it coerces all values to NA. The format I am looking for is: "2017-01"

library(lubridate)
df<- data.frame(Date=c("2017-01-01","2017-01-02","2017-01-03","2017-01-04",
                       "2018-01-01","2018-01-02","2018-02-01","2018-03-02"),
            N=c(24,10,13,12,10,10,33,45))
df$Date <- as_datetime(df$Date)
df$Date <- ymd(df$Date)
df$Date <- strftime(df$Date,format="%Y-%m")

提前谢谢!

推荐答案

lubridate仅处理日期,并且日期为天.但是,就像alistaire所说的那样,您可以按每月要工作的月份对它们进行铺垫:

lubridate only handle dates, and dates have days. However, as alistaire mentions, you can floor them by month of you want work monthly:

library(tidyverse)

df_month <-
  df %>%
  mutate(Date = floor_date(as_date(Date), "month"))

例如想要按月汇总,只需group_by()summarize().

If you e.g. want to aggregate by month, just group_by() and summarize().

df_month %>%
  group_by(Date) %>%
  summarize(N = sum(N)) %>%
  ungroup()

#> # A tibble: 4 x 2
#>  Date           N
#>  <date>     <dbl>
#>1 2017-01-01    59
#>2 2018-01-01    20
#>3 2018-02-01    33
#>4 2018-03-01    45

这篇关于在R中将日期格式化为年月的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆