r - 自定义函数来处理 Excel 中的不同日期格式,尝试使用 curly curly

标签 r function dplyr tidyverse eval

我有一个使用 read_excel 从 Excel 导入的数据框,如下所示:

主要任务是处理不同格式的日期:

我想将它实现为自定义函数(而且我根本不擅长创建函数):

df <- structure(list(date = c("40574", "40861", "40870", "40990", "07.03.2022", 
"14.03.2022", "16.03.2022", "27.03.2022", "24.03.2022", "24.03.2022"
)), row.names = c(NA, -10L), class = c("tbl_df", "tbl", "data.frame"
))

# A tibble: 10 x 1
   date      
   <chr>     
 1 40574     
 2 40861     
 3 40870     
 4 40990     
 5 07.03.2022
 6 14.03.2022
 7 16.03.2022
 8 27.03.2022
 9 24.03.2022
10 24.03.2022

我用这段代码解决了这个任务:

library(tidyverse)
library(janitor)
library(lubridate)

df %>% 
  mutate(new_col = excel_numeric_to_date(as.numeric(as.character(date)), date_system = "modern"), .before=1) %>% 
  mutate(date = ifelse(!str_detect(date, '\\.'), NA_character_, date)) %>% 
  mutate(date = dmy(date)) %>% 
  mutate(date = coalesce(date, new_col), .keep="unused")

通过这段代码,我想用这段代码创建一个自定义函数:

mixed_dateColumn_excel <- function(df, x) {
  x <- {{x}}
  df %>% 
    mutate(new_col = excel_numeric_to_date(as.numeric(as.character(x)), date_system = "modern"), .before=1) %>% 
    mutate(x = ifelse(!str_detect(x, '\\.'), NA_character_, x)) %>% 
    mutate(x = dmy(x)) %>% 
    mutate(x = coalesce(x, new_col), .keep="unused")
}

我想知道为什么:

这不起作用:

mixed_dateColumn_excel(df, "date")

这也不起作用:

mixed_dateColumn_excel(df, date)

这有效:

mixed_dateColumn_excel(df, df$date)

最佳答案

与您关于对函数进行编程的问题分开,但如果有人来这里寻求解决原始问题:您可以使用单个看门人函数来做到这一点,更强大的 convert_to_date() 来了在 excel_numeric_to_date() 之后。

library(tidyverse)
library(janitor)
df %>%
  mutate(new_col = convert_to_date(date, character_fun = lubridate::dmy))

# A tibble: 10 x 2
   date       new_col   
   <chr>      <date>    
 1 40574      2011-01-31
 2 40861      2011-11-14
 3 40870      2011-11-23
 4 40990      2012-03-22
 5 07.03.2022 2022-03-07
 6 14.03.2022 2022-03-14
 7 16.03.2022 2022-03-16
 8 27.03.2022 2022-03-27
 9 24.03.2022 2022-03-24
10 24.03.2022 2022-03-24

它首先转换 Excel 数字,然后对其余值应用日期转换函数。

关于r - 自定义函数来处理 Excel 中的不同日期格式,尝试使用 curly curly,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71844502/

相关文章:

r - 如何在绘图仪表图中计算指针位置

function - 有没有办法在 R 的函数中使用两个 '...' 语句?

r - 传递 `chr` 类型参数并更新嵌套函数的内容以在 R 中返回?

r - 如何使用 dplyr 在特定列中查找哪些组具有相同的值?

r - 将 docx 转换为 Rmarkdown

python - 将整数表示为分数形式的倒数的函数

c++ - 为什么局部变量的值(它的地址存储在全局变量中)在函数执行完成后被释放

R Shiny ;如何使用来自 selectInput 的多个输入传递到 dplyr 中的 'select' 选项?

r - 用于配对 Wilcoxon 检验的带有 p 值的动画 fiddle /箱线图

R:如何写出一个 data.frame 以便我可以将它粘贴到 SO 中供其他人阅读?