使用dplyr在不创建临时数据框的情况下获取过滤后数据框中年末日期列的最大值
Hey Thomas,
Great question! You’re right—you don’t need to create a temporary data frame to get that single value. Here are a few clean, pipe-friendly ways to achieve what you want:
1. Extract the column first with pull()
This approach filters the December entries, pulls the Date column into a vector, then takes the max directly:
library(dplyr) library(zoo) df <- data.frame(Date = as.yearmon(2000 + 1:30/12), x = 1:30) max_dec_date <- df %>% filter(format(Date, "%m") == "12") %>% pull(Date) %>% max() max_dec_date # [1] "Dec 2001"
2. Use summarize() to compute the max in the chain
You can also compute the max within a summarize() step, then pull the result to get a single value:
max_dec_date <- df %>% filter(format(Date, "%m") == "12") %>% summarize(max_date = max(Date)) %>% pull(max_date) max_dec_date # [1] "Dec 2001"
3. Faster alternative with cycle() (no string formatting)
Since yearmon objects have a built-in way to retrieve the month number via cycle(), we can avoid converting dates to strings entirely—this is more efficient for large datasets:
max_dec_date <- df %>% filter(cycle(Date) == 12) %>% pull(Date) %>% max() max_dec_date # [1] "Dec 2001"
All these methods eliminate the need for a temporary data frame and give you the single yearmon value you’re looking for directly.
Content of the question originates from Stack Exchange, asked by Thomas Philips

