Select Time in R

Asked

Viewed 94 times

2

I have the following df with date in date and time format:

MATRICULA <- c('111','222','333','444','555')
DATA_INICIO <- c('17/03/2017 22:25','15/01/2019 20:01', 
'10/12/2013 01:01','10/10/2018 14:22','22/04/2015 07:29')
DADOS <- data.frame(MATRICULA,DATA_INICIO)

How do I select only the Time and create a column with it?

2 answers

3

You can do it like this:

library(tidyverse)
library(lubridate)

DADOS %>% 
  mutate(DATA_INICIO = dmy_hm(DATA_INICIO)) %>% 
  separate(DATA_INICIO, into = c('DATA', 'HORA'), sep = ' ')

In this way, the DATA and the HORA stand in separate columns.

2

Only on R basis.

DADOS$DATA_INICIO <- as.POSIXct(DADOS$DATA_INICIO, format = "%d/%m/%Y %H:%M")
DADOS$HORA <- format(DADOS$DATA_INICIO, "%H")

DADOS
#  MATRICULA         DATA_INICIO HORA
#1       111 2017-03-17 22:25:00   22
#2       222 2019-01-15 20:01:00   20
#3       333 2013-12-10 01:01:00   01
#4       444 2018-10-10 14:22:00   14
#5       555 2015-04-22 07:29:00   07

If you want, you can use

lubridate::hour(DADOS$DATA_INICIO)

after converting the column DATA_INICIO for class "POSIXt".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.