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

使用map_int()向量化自定义函数:计算时段工作日数并新增数据列

Hey there! Let's get your workday count column added using purrr's mapping functions (perfect for paired date columns like yours). Here's a step-by-step breakdown:

Step 1: Complete Your Sample Dataframe

First, let's fill in the missing end_date values to create a working example:

df <- data.frame(
  start_date = c('2018-1-1', '2018-2-1'),
  end_date = c('2018-1-10', '2018-2-15') # Example end dates for testing
)
Step 2: Use map2_int() to Calculate Workdays

Your fx_weekdays function takes two date arguments, so map2_int() is ideal here—it pairs elements from two vectors and returns integer output (exactly what we need for a count). Here's how to integrate it into your dataframe:

library(tidyverse)
library(lubridate)

# Your custom workday function (repeated for reference)
fx_weekdays <- function(start_date, end_date){
  start_date <- as_date(start_date)
  end_date <- as_date(end_date)
  sum(!weekdays(seq(start_date, end_date, "days")) %in% c("Friday", "Saturday"))
}

# Add the new workday count column
df <- df %>%
  mutate(workday_count = map2_int(start_date, end_date, fx_weekdays))

How This Works:

  • map2_int(start_date, end_date, fx_weekdays): Iterates over each pair of start_date and end_date values, applies your function, and returns an integer vector of results.
  • mutate(): Adds this vector as a new column (workday_count) directly to your original dataframe.
Alternative: Row-wise Iteration with pmap_int()

If you prefer working with full rows (useful if you ever need to pass more than two columns to a function), you can use pmap_int() instead:

df <- df %>%
  mutate(workday_count = pmap_int(., ~fx_weekdays(..1, ..2)))

Here, ..1 and ..2 refer to the first and second columns of your dataframe (you could also explicitly name them with list(start_date, end_date) for clarity).

Quick Result Check

For our sample dataframe:

  • The first row (2018-1-1 to 2018-1-10) should return 8 workdays (excluding Jan 5 and 6)
  • The second row (2018-2-1 to 2018-2-15) should return 11 workdays (excluding Feb 2,3,9,10)

内容的提问来源于stack exchange,提问作者ronencozen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:37:36