我有一个使用 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/