1

I am trying to separate a column with time increments that are in a character format.

The format is MM:SS for most observations, but there are a few with the HH:MM:SS format. I am trying to separate into columns based on the ":" so I can reduce the times to seconds to preform some basic analysis.

I would like to get this:

     Time
    1   11:15
    2   12:36
    3 1:15:17

into this:

        Hour  Minuet Second 
    1    NA     11   15
    2    NA     12   36
    3     1     15   17     

I have tried

      separate(df, time, into = c("Hours", "Minuets", "Seconds"), by = ":")

Which returns:

         Hour  Minuet Second 
    1    11     15   NA
    2    12     36   NA
    3     1     15   17   
maribou912
  • 13
  • 3

1 Answers1

0

This should work

library(dplyr)
library(tidyr)
df %>%
  separate(time, c("Hour", "Minute", "Second"), sep = ":", fill = "left")
# -------------------------------------------------------------------------

#   Hour Minute Second
# 1 <NA>     11     15
# 2 <NA>     12     36
# 3    1     15     17

Data

#dput(df)
df <- structure(list(time = c("11:15", "12:36", "1:15:17")), class = "data.frame", row.names = c(NA, 
-3L))

?separate

fill If sep is a character vector, this controls what happens when there are not enough pieces. There are three valid options:

>"warn" (the default): emit a warning and fill from the right

>"right": fill with missing values on the right

>"left": fill with missing values on the left
deepseefan
  • 3,701
  • 3
  • 18
  • 31