我必須結合大量來自 excel 的分析師電子表格,似乎每周他們都會找到一種新的方式來激怒我。這是我的最新問題:
data <- tibble(date_column = c(44673, 44674, "2022-04-25"))
# A tibble: 3 x 1
date_column
<chr>
1 44673
2 44674
3 2022-04-25
我嘗試了多種方法來測驗它是否可以是一個數字,然后將其轉換為日期,如果不轉換為另一種方式,如下所示:
library(tidyverse)
library(lubridate)
data %>%
mutate(date_column = case_when(
!is.na(as.numeric(date_column)) ~ as.Date(date_column, origin = "1899-12-30"),
is.na(as.numeric(date_column)) ~ parse_date_time(date_column, orders = c("mdY","Ymd T", "Ymd"))))
# which throws a
Error: Problem with `mutate()` column `date_column`.
i `date_column = case_when(...)`.
x character string is not in a standard unambiguous format
Run `rlang::last_error()` to see where the error occurred.
In addition: Warning message:
Problem with `mutate()` column `date_column`.
i `date_column = case_when(...)`.
i NAs introduced by coercion
我覺得這一定是一個非常普遍的問題,之前已經解決了。非常感謝幫助。
uj5u.com熱心網友回復:
試試看門人convert-to-date
:
library(tidyverse)
library(janitor)
#>
#> Attaching package: 'janitor'
#> The following objects are masked from 'package:stats':
#>
#> chisq.test, fisher.test
tribble(~date,
"44673",
"44674",
"2022-04-25") |>
mutate(clean_date = convert_to_date(date))
#> # A tibble: 3 × 2
#> date clean_date
#> <chr> <date>
#> 1 44673 2022-04-22
#> 2 44674 2022-04-23
#> 3 2022-04-25 2022-04-25
由reprex 包于 2022-05-05 創建(v2.0.1)
uj5u.com熱心網友回復:
一個可能的解決方案,基于openxlsx::convertToDate
:
library(tidyverse)
library(openxlsx)
data <- tibble(date_column = c(44673, 44674, "2022-04-25"))
coalesce(suppressWarnings(convertToDate(data$date_column)) %>%
as.character(), data$date_column)
#> [1] "2022-04-22" "2022-04-23" "2022-04-25"
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/470807.html
下一篇:如何獲取日期輸入的值?