创建一个新列,其中包含给定年月 (dplyr) 的每个月 YMD 日期

问题描述 投票:0回答:1

我想创建一个新列,以 ymd 格式显示每个月的最后一天,并在同一行中给出年份和月份。像这样的东西:

month_year    end_month
Jan 2022      31/01/2022
Jan 2022      31/01/2022
Feb 2022     28/02/2022
March 2022    31/03/2022
library(zoo)
library(tidyverse)

# Print data example with specific columns
dput(df[1:20,c(1,19,23)])

输出:

structure(list(id = 1:20, posted_date = c("2023-03-12 00:00:00", 
"2023-03-13 00:00:00", "2023-03-20 00:00:00", "2023-03-08 00:00:00", 
"2023-03-16 00:00:00", "2023-03-20 00:00:00", "2023-03-09 00:00:00", 
"2023-03-20 00:00:00", "2023-03-13 00:00:00", "2023-03-21 00:00:00", 
"2023-03-07 00:00:00", "2023-03-08 00:00:00", "2023-03-19 00:00:00", 
"2023-03-19 00:00:00", "2023-03-12 00:00:00", "2023-03-12 00:00:00", 
"2023-03-20 00:00:00", "2023-03-20 00:00:00", "2023-03-09 00:00:00", 
"2023-03-12 00:00:00"), month_year = structure(c(2023.16666666667, 
2023.16666666667, 2023.16666666667, 2023.16666666667, 2023.16666666667, 
2023.16666666667, 2023.16666666667, 2023.16666666667, 2023.16666666667, 
2023.16666666667, 2023.16666666667, 2023.16666666667, 2023.16666666667, 
2023.16666666667, 2023.16666666667, 2023.16666666667, 2023.16666666667, 
2023.16666666667, 2023.16666666667, 2023.16666666667), class = "yearmon")), row.names = c(NA, 
-20L), class = c("tbl_df", "tbl", "data.frame"))

我使用解决方案here进行了一些尝试,如下所示:

job_posts %>% 
   group_by(month_year = as.yearmon(Date)) %>%
   summarise(First = floor_date(first(Date), 'month'), 
             Last = ceiling_date(last(Date), 'month')-1)

但是我不断收到此错误消息,但我很困惑,因为我的 df 中的“month_year”确实是yearmon格式,而不是数字,所以我认为上面的代码应该有效? “group_by(., Month_year = as.yearmon(Date)) 中的错误: 由

as.numeric()
中的错误引起: !无法将类型“closure”强制转换为“double”类型的向量”

r datetime dplyr lubridate zoo
1个回答
0
投票

您想做的事情有三种不同的可能性:

1.获取每个月的第一个和最后一个posted_date

df |> mutate(first = first(posted_date), last = last(posted_date), .by = month_year)

但是行不按顺序排列,并且数据中的第一行和最后一行具有相同的日期,因此我们最终得到第一列和最后一列的相同日期,所以我认为这不是您想要的。

2.获取每个月最早和最晚的日期

df |> mutate(first = min(posted_date), last = max(posted_date), .by = month_year)

但显然,如果数据丢失了几天,那么我们将无法获得每个月的绝对最后天。

3.获取每个月_年的第一天和最后一天

df |> summarise(first = as.Date(month_year[1]), last = as.Date(month_year[1] + (1/12))-1, .by = month_year)

输出:

# A tibble: 1 × 3
  month_year first      last      
  <yearmon>  <date>     <date>    
1 Mar 2023   2023-03-01 2023-03-31

我相信这最后一个就是您正在寻找的。

© www.soinside.com 2019 - 2024. All rights reserved.