【问题标题】:map_int() to vectorize user defined functionmap_int() 向量化用户定义的函数
【发布时间】:2018-05-03 08:11:49
【问题描述】:

我定义了以下函数,它计算一个周期内的工作日数。

library(tidyverse)
library(lubridate)
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"))
}

接下来我想使用 map_int() 循环以下数据框,并添加一个新列来捕获结果。

df <- data.frame(start_date=c('2018-1-1','2018-2-1'),
           end_date=c('2018-1-31','2018-2-28'))

df %>% 
  mutate(n_weekday = map_int(df, fx_weekdays(start_date, end_date)))

我收到一个错误。

mutate_impl(.data, dots) 中的错误:评估错误:'from' must 长度为 1。

我不知道我错过了什么,因为以下示例按预期工作。

fx_weekdays('2018-3-12', '2018-4-12')

【问题讨论】:

    标签: r


    【解决方案1】:

    改用map2_int怎么样?

    library(tidyverse)
    library(lubridate)
    df %>% mutate(n_weekday = map2_int(start_date, end_date, fx_weekdays))
    #>   start_date  end_date n_weekday
    #> 1   2018-1-1 2018-1-31        23
    #> 2   2018-2-1 2018-2-28        20
    

    【讨论】:

    • map_int 和 map2_int 有什么区别?
    • @ronencozen,map2 函数允许您提供两个参数以在提供给函数时并行迭代(而不是 map 的一个参数)。在这种情况下,我们需要将start_dateend_date 都提供给fx_weekdays()。为了比较,不妨看看purrr.tidyverse.org/reference/map.htmlmap 示例与purrr.tidyverse.org/reference/map2.html 的一些map2 示例
    【解决方案2】:

    我不确定您是否需要map_int,但是您可以使用rowwise 来完成

    df %>% 
      rowwise() %>% 
      mutate(n_weekday = fx_weekdays(start_date, end_date))
    
    #  start_date end_date  n_weekday
    #  <fct>      <fct>         <int>
    #1 2018-1-1   2018-1-31        23
    #2 2018-2-1   2018-2-28        20
    

    我相信您一定知道您也可以使用 base R mapply 来执行此操作。

    df$n_weekday <- mapply(fx_weekdays, df$start_date, df$end_date)
    
    df
    #  start_date  end_date n_weekday
    #1   2018-1-1 2018-1-31        23
    #2   2018-2-1 2018-2-28        20
    

    【讨论】:

    • 有趣的方法,谢谢!
    猜你喜欢
    • 2018-11-18
    • 2020-10-03
    • 2019-11-14
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 2017-11-15
    • 1970-01-01
    • 2020-04-12
    相关资源
    最近更新 更多