Tidyverse Parse Date String

问题描述 投票:1回答:1

我在数据框中有一个“日期”列,在日期之后有一个空格。我想FIND空间,然后去LEFT到那个位置减1点,并将该字符串转换为日期。这是一个代表性的例子:

library(tidyverse)
library(lubridate)

my_sales <- c(10, 15, 20, 15)
my_dates <- c("12/30/02 0:00", "1/4/03 0:00", "1/11/03 0:00", "1/19/03 0:00")
df <- data.frame(my_sales, my_dates)
df$my_dates <- as.character(df$my_dates)

df$my_dates_temp1 <- str_sub(df$my_dates, 1, str_locate(df$my_dates, ' ')[, 1]-1)
head(df)

>   my_sales      my_dates my_dates_temp1
> 1       10 12/30/02 0:00       12/30/02
> 2       15   1/4/03 0:00         1/4/03
> 3       20  1/11/03 0:00        1/11/03
> 4       15  1/19/03 0:00        1/19/03

我的问题是当我尝试将my_dates_temp1转换为约会时。

基地R.

as.Date(df$my_dates_temp1)
> Error in charToDate(x) : 
>   character string is not in a standard unambiguous format

lubridate

lubridate::as_date(df$my_dates_temp1)
> [1] NA NA NA NA
> Warning message:
> All formats failed to parse. No formats found. 

这不是一种可以转换为日期的格式,我该如何转换它?

r date tidyverse lubridate
1个回答
2
投票

我们需要format,因为它不是"YYYY-MM-DD"的默认格式

as.Date(df$my_dates_temp1, "%m/%d/%y")
#[1] "2002-12-30" "2003-01-04" "2003-01-11" "2003-01-19"

或使用

lubridate::mdy(df$my_dates_temp1)
#[1] "2002-12-30" "2003-01-04" "2003-01-11" "2003-01-19"
© www.soinside.com 2019 - 2024. All rights reserved.