使用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:
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 )
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 ofstart_dateandend_datevalues, 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.
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).
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

