Ogunyinka
Ogunyinka

Reputation: 1

Date data- type in R programing

I am currently working on Google data analytic capstone cyclistic. I am to add a column called date, day, month and year. I have install necessary packages. I have a column called $started_at which contain date and time in this format "4/26/2020 17:45" and it is in chr (character) And I type the code like this

df$date<-as.Date(df$started_at)

The output said Error in chartodate(x) Character string is not in a standard unambiguous format

I also tried

df$date<-as.Date(df$started_at,format = "%y%m%d")

The date column brings NA

I also tried

df$started_at = strptime(df$started_at,"%y-%m-
%d %H: %M: %S")

The output of this is also NA

What Is the problem

I am currently working on Google data analytic capstone cyclistic.

I am to add a column called date, day, month and year.

I have install necessary packages.

I have a column called $started_at which contain date and time in this format "4/26/2020 17:45" and it is in chr (character)

And I type the code like this


df$date<-as.Date(df$started_at)

The out put said

Error in chartodate(x)

Character string is not in a standard unambiguous format

I also tried


df$date<-as.Date(df$started_at,format = "%y%m%d")

The date column brings NA

I also tried


df$started_at = strptime(df$started_at,"%y-%m-

%d %H: %M: %S")

The out put of this is also NA

What Is the problem

Upvotes: 0

Views: 22

Answers (1)

Mark
Mark

Reputation: 12558

The issue is that your started_at column is a datetime, not a date. To convert it to a date, you have to pass in the format, using the strptime formatting syntax:

df$started_at <- as.POSIXct(df$started_at, format = "%m/%d/%Y %H:%M") |> as.Date()
# or
df$started_at <- as.Date(df$started_at, format = "%m/%d/%Y %H:%M")
#or
library(lubridate)
mdy_hm(df$started_at) |> as_date()

Data:

df <- data.frame(
  started_at = "4/26/2020 17:45")

Upvotes: 0

Related Questions