在 R 中将日期格式化为年月

Format Date to Year-Month in R

我想以年月格式保留当前日期列作为日期。它目前被转换为 chr 格式。我试过 as_datetime 但它将所有值强制为 NA。 我要找的格式是:“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")

提前致谢!

您可以使用 zoo::as.yearmon() 函数解决此问题。遵循解决方案:

library(tidyquant)
library(magrittr) 
library(dplyr)

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 %<>% mutate(Date = zoo::as.yearmon(Date))

lubridate只处理日期,日期有天。但是,正如 alistaire 提到的那样,您可以按每月想要工作的月份来划分它们:

library(tidyverse)

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

如果你想要按月汇总,只需 group_by()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

您可以使用 cut 函数,并使用 breaks="month" 将日期中的所有日期转换为该月的第一天。因此,同一个月内的任何日期在新创建的列中都将具有相同的日期。

这对于按月对数据框中的所有其他变量进行分组很有用(基本上就是您要尝试做的事情)。但是 cut 会创建一个因子,但这可以转换回日期。所以你的数据框中仍然可以有日期 class。

你就是不能去掉约会中的那一天(因为那一天不是约会……)。之后,您可以为轴或表创建一个漂亮的格式。例如:

true_date <-
  as.POSIXlt(
    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"
    ),
    format = "%F"
  )

df <-
  data.frame(
    Date = cut(true_date, breaks = "month"),
    N = c(24, 10, 13, 12, 10, 10, 33, 45)
  )

## here df$Date is a 'factor'. You could use substr to create a formated column
df$formated_date <- substr(df$Date, start = 1, stop = 7)

## and you can convert back to date class. format = "%F", is ISO 8601 standard date format

df$true_date <- strptime(x = as.character(df$Date), format = "%F")

str(df)