I am on a case study for a Analytics course. I loaded various csv-files into R along with common libraries to use such as tidyverse, janitor etc.
Now, I have 2 datasets that have date-time in one columnm and are chr type. One is sleep or sleep_new. I added pictures and code to illustrate my current results below.
I manage either to separate the two columns and they remain chr types.I can not transform the time column in only time. R will always add todays date to it.
On the flip side when I manage to add the date-time format and change the type, I can not split the column without loosing the type or getting date added to time.
In the end I want to only maintain the two new columns in date and time format, not chr.
By now I am just blind to my mistakes as I tried a gazillion of ways but ran into errors on one side or the other. Obviously I am a bloody beginner and my logical thinking for code is limited.
Would be happy to get some help.
I have used the following code pieces so far:
1.Changing from chr to dttm type
sleep_new <- sleep %>%
rename(datetime = SleepDay)%>%
mutate(datetime = as.POSIXct(datetime, format = "%m/%d/%Y %H:%M:%S"))
this works but know I can't manage to split it into two separate columns
more precisely I want to split the date time column into date and time and keep the position to two columns [2][3] without having the datetimne column.
2. For splitting the column I used:
sleep_new$date <- format(sleep_new$datetime, format = "%m/%d/%y")
sleep_new$time <- format(sleep_new$datetime, format = "%H:%M:%S")
- this works but put the column position to the end of the table and obviously keeps the date time column
3. Another post on Stackoverflow suggested this:
df$Time <- format(as.POSIXct(df$Start,format="%Y:%m:%d %H:%M:%S"),"%H:%M:%S")
df$Date <- format(as.POSIXct(df$Start,format="%Y:%m:%d %H:%M:%S"),"%Y:%m:%d")
which I translated to my case:
sleep_new$time <- format(as.POSIXct(sleep_new$datetime,format="%Y:%m:%d %H:%M:%S"),"%H:%M:%S")
sleep_new$date <- format(as.POSIXct(sleep_new$datetime,format="%Y:%m:%d %H:%M:%S"),"%Y:%m:%d")
- however it is equally not working as it out puts the two columns in chr type.
Here are the sample images: