r - 在R中将字符列转换为具有混合数字和日期的日期

标签 r excel date

这个问题在这里已经有了答案:





Fix date column in excel that imported to R as a mix of integers and character dates

(2 个回答)


上个月关门。




我必须结合大量来自 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 
我觉得这一定是一个非常普遍的问题,之前已经解决了。非常感谢帮助。

最佳答案

试试看门人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 package 创建于 2022-05-05| (v2.0.1)

关于r - 在R中将字符列转换为具有混合数字和日期的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72129893/

相关文章:

r - 无法安装 xkcd 字体

r - 使用 dplyr 到 group_by 并按组有条件地改变数据帧

c# - 如何使用 NPOI 获得非参差不齐的右列

mysql - 无论年份如何,在mysql中选择两个日期之间的数据

返回最接近 R 中给定日期的日期

r - 在 R 文本挖掘中从文本语料库中删除 "english"停用词时 UTF-8 无效

r - Docker-R创建多个进程

excel - 如果字段为空,则将 CONCATENATE 向上挤压,这样空间间隙就不会太大

Excel - 查看 IP 地址是否包含在子网列表中的公式

Javascript getTimezoneOffset 返回错误的偏移量?