If statement with period data type in R

Viewed 92

Working with the time class in R sometimes can be a little challenging.

My dataset is a single column of day-times (H/M/S). Nevertheless, when I import the dataset, R classifies it as chr.

What I want to do is to create an additional column that has value equal to 1 in case the time is after 10.30.00, else 0.

Via lubridate I managed to convert the data into the Period data type:

db %>% dplyr::select(Time) %>% mutate(Time = lubridate::hms(Time))

Nevertheless, I do not know exactly how to apply an if statement to the resulting column Time of class Period as this:

%>% ifelse(Time > 10H 30M 0S, 1, 0)

does not work.

Any hint on how to get this simple task done? Many thanks!

2 Answers

You can do as follows.

library(dplyr)
library(lubridate)

data <- tibble(time = hms(c('10:29:30', '14:12:55')))

data %>%
  mutate(after = if_else(time > hms('10:30:00'), 1, 0))

#   time        after
#   <Period>    <dbl>
# 1 10H 29M 30S     0
# 2 14H 12M 55S     1

An option is to coerce to integer with as.integer

library(lubridate)
library(dplyr)
data %>% 
   mutate(after = as.integer(time > hms('10:30:00')))
# A tibble: 2 x 2
#  time        after
#  <Period>    <int>
#1 10H 29M 30S     0
#2 14H 12M 55S     1

data

data <- tibble(time = hms(c('10:29:30', '14:12:55')))
Related