【问题标题】:How to maintain date format when after applying function应用函数后如何维护日期格式
【发布时间】:2023-02-07 01:15:14
【问题描述】:

我的数据框的日期信息格式不正确。

date = c("18102016", "11102017", "4052017", "18102018", "3102018")
df <- data.frame(date = date, x1 = 1:5, x2 = rep(1,5)) 

我已经编写了函数 fix_date_all(),它在应用于向量 df$date 时进行正确的格式化

fix_date_all<- function(date){
  fix_date <- function(d) {
    if (nchar(d) != 8) d <- paste0("0", d)
    
    dd <- d %>% substr(1,2)
    mm <- d %>% substr(3,4)
    yyyy <- d %>% substr(5,8)
    
    d <- paste0(dd, ".", mm, ".", yyyy) %>% as.Date("%d.%m.%Y")
    
    d
  }
  
  lapply(date, fix_date)
}

fix_date_all(df$date)

现在我想使用类似 tidyverse 的样式将此变量转换为适当的日期格式:

df %>% mutate(across(date, fix_date_all))

然而,当以 tidyverse 风格使用它时,日期会搞砸。

   date x1 x2
1 17092  1  1
2 17450  2  1
3 17290  3  1
4 17822  4  1
5 17807  5  1

【问题讨论】:

    标签: r date mutate


    【解决方案1】:

    lapply 调用的输出是 list

    fix_date_all(df$date)
    [[1]]
    [1] "2016-10-18"
    
    [[2]]
    [1] "2017-10-11"
    
    [[3]]
    [1] "2017-05-04"
    
    [[4]]
    [1] "2018-10-18"
    
    [[5]]
    [1] "2018-10-03"
    

    我们需要用c把它压平

    library(dplyr)
    df %>% 
       mutate(date = fix_date_all(date) %>%
       do.call(c, .))
    

    -输出

            date x1 x2
    1 2016-10-18  1  1
    2 2017-10-11  2  1
    3 2017-05-04  3  1
    4 2018-10-18  4  1
    5 2018-10-03  5  1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-16
      • 2016-02-04
      • 2021-07-06
      相关资源
      最近更新 更多