You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 19:59:09