0

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:

enter image description here

enter image description here

Phil
  • 7,287
  • 3
  • 36
  • 66
Patrick
  • 1
  • 1
  • 1
    Please use `dput()` to share your data rather than uploading an image of it. See also: https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – br00t May 30 '23 at 20:16

1 Answers1

1

Base R doesn’t come with a “time-only” class. You could use the one from the hms package:

x <- "2023-05-30 12:30:00"
dttm <- strptime(x, "%Y-%m-%d %H:%M:%S")
data.frame(
  dttm = as.POSIXct(dttm),
  date = as.Date(dttm),
  time = hms::as_hms(dttm)
)
#>                  dttm       date     time
#> 1 2023-05-30 12:30:00 2023-05-30 12:30:00
Mikko Marttila
  • 10,972
  • 18
  • 31