【发布时间】:2019-02-15 04:41:53
【问题描述】:
我在日期后有一个空格的数据框中有一个“日期”列。我想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::as_date(df$my_dates_temp1)
> [1] NA NA NA NA
> Warning message:
> All formats failed to parse. No formats found.
这不是可以转换为日期的格式,我该如何转换?
【问题讨论】:
-
或者你可以使用
as.POSIXct(df$my_dates, format = "%m/%d/%y %H:%M")。
标签: r date tidyverse lubridate