【问题标题】:R lubridate customise week_start by yearR lubridate 按年份自定义 week_start
【发布时间】:2021-11-12 23:48:03
【问题描述】:

这是我的示例数据,我想在 wday 函数中从 lubridate 包自定义 week_start

mydate <- data.frame(Date = c("13/09/2021", "13/09/2020", "13/09/2019", "13/09/2018"))

例如,一周的开始是year %% 7。但是当我运行我的代码时出现以下错误

numerical expression has 4 elements: only the first used

library(lubridate)
library(dplyr)

mydate2 <- mydate %>%
  mutate(Date = ymd(as.Date(as.factor(Date), format = "%d/%m/%Y")),
         years = year(Date),
         days = wday(Date, label = TRUE, week_start = years %% 7)) 

我想我需要使用purrr 中的map 函数。试了几次,还是不行。

非常感谢。

【问题讨论】:

    标签: r dplyr purrr lubridate


    【解决方案1】:

    您可以使用map2_chr 为每个基于year 值的Date 自定义week_start

    library(dplyr)
    library(lubridate)
    
    mydate %>%
      mutate(Date = as.Date(Date, format = "%d/%m/%Y"),
             years = year(Date),
             days = map2_chr(Date, years, 
                      ~as.character(wday(.x, label = TRUE, week_start = .y %% 7))))
    
    
    #        Date years days
    #1 2021-09-13  2021  Mon
    #2 2020-09-13  2020  Sun
    #3 2019-09-13  2019  Fri
    #4 2018-09-13  2018  Thu
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-18
      • 1970-01-01
      相关资源
      最近更新 更多