New Data Analyst need help about date and time in R

Hi, I'm new in this area, I just finished the data analyst google course, also I just finished my case study, but I have a doubt, I spent a lot of time to study, and I was able to solve many things. but i have a question about with one column (activityHour) look like this

chr [1:22099] "4/12/2016 0:00"

its a chr column, so, when I try to separate this column in date and time format, I always got an NA,. either if I use the function as.numertic,, strptime, as follow:

Hourly_Intensities$ActivityHour <- as.numeric(as.character(Hourly_Intensities$ActivityHour))
Warning message:
NAs introduced by coercion

Hourly_Intensities$ActivityHour <- strptime(df$cHourly_Intensities$ActivityHour, format='%Y-%m-%d %H:%M:S', tz=Sys.timezone())
Error in df$cHourly_Intensities :
object of type 'closure' is not subsettable

I really appreciate if someone could help me in this, separate this chr column into date and time without getting and NA

I'm new in this, and I really love it, I hope can do this forever =P

thank you very much

It is not clear to me if you want to split ActivityHour into two columns or if you want to convert it to a Date-Time value. The code below shows how to do both of those things. I assumed the date portion is formatted as m/d/y. If it is d/m/y, use the dmy_hm() function to convert it to a Date-Time.

#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#>     date, intersect, setdiff, union

#Separate the day and time portions of ActivityHour
DF <- data.frame(ActivityHour = c("4/12/2016 0:00", "5/01/2016 13:54"))
#> 'data.frame':    2 obs. of  1 variable:
#>  $ ActivityHour: chr  "4/12/2016 0:00" "5/01/2016 13:54"
DF <- DF |> separate(col = ActivityHour, into = c("Date", "Time"), sep = " ")
#>        Date  Time
#> 1 4/12/2016  0:00
#> 2 5/01/2016 13:54
#> 'data.frame':    2 obs. of  2 variables:
#>  $ Date: chr  "4/12/2016" "5/01/2016"
#>  $ Time: chr  "0:00" "13:54"

#Make ActivityHour a Date-Time value
DF <- data.frame(ActivityHour = c("4/12/2016 0:00", "5/01/2016 13:54"))
DF$ActivityHour <- mdy_hm(DF$ActivityHour)
#>          ActivityHour
#> 1 2016-04-12 00:00:00
#> 2 2016-05-01 13:54:00

Created on 2023-03-17 with reprex v2.0.2

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.