How can I divide single column contains 2 information, dividing with ' ' into 2 columns?

Hello, I want to divide a column whose format is 'chr' into 2 columns.
The data structure given is like this :

         date_and_time
1     2019-09-01 00:00:00
2     2019-09-01 00:00:30
3     2019-09-01 00:01:00
...           ...

As you can see, 2 information are in one column, and it was divided by one 'space'. And I want to make a data like this :

         date         time
1     2019-09-01    00:00:00
2     2019-09-01    00:00:30
3     2019-09-01    00:01:00
...      ...           ...

I searched by myself and was told 'str_split' is used to deal with this, but still don't know so how to devide the column and ultimately convert this into vector or dataframe form to merge with other data. Please help me!

Your easiest bet is probably tidyr::separate(). This will split the column in two and drop the original column. You could then go on to use {lubridate} and {hms} to properly format hte resulting columns as dates and times:

df <- 
  dplyr::tibble(
    date_and_time = c(
      "2019-09-01 00:00:05",
      "2019-09-01 00:30:00",
      "2019-09-01 01:00:00"
    )
  )

# split into two columns
(df <- 
  tidyr::separate(
    data = df,
    col = date_and_time,
    into = c("date", "time"),
    sep = " "
  ))
#> # A tibble: 3 × 2
#>   date       time    
#>   <chr>      <chr>   
#> 1 2019-09-01 00:00:05
#> 2 2019-09-01 00:30:00
#> 3 2019-09-01 01:00:00

# fix data types
dplyr::mutate(
  .data = df,
  date = lubridate::ymd(date),
  time = hms::as_hms(time)
)
#> # A tibble: 3 × 2
#>   date       time    
#>   <date>     <time>  
#> 1 2019-09-01 00:00:05
#> 2 2019-09-01 00:30:00
#> 3 2019-09-01 01:00:00

Created on 2022-10-21 with reprex v2.0.2

1 Like

Thank you so much!!!!!!!!!!!!!!!

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.