How to add a column in a table?

Hi. I have a table with a column "date & time" (dd/mm/yyyy hh:mm:ss). I need to add a column with a condition that if the date is before 10/01/2022 00:00:00 its 'a holiday' or ' workday' otherwise.

Here are two methods for making the new column. One uses a function from base R and the other uses the lubridate package.

#Using base R as.POSIXct()
DF <- data.frame(DateTime = c("08/01/2022 08:15:34", 
                              "10/01/2022 13:24:53"))

DF
#>              DateTime
#> 1 08/01/2022 08:15:34
#> 2 10/01/2022 13:24:53
Boundary <- as.POSIXct("10/01/2022 00:00:00", format = "%d/%m/%Y %H:%M:%S")

DF$Flag <- ifelse(as.POSIXct(DF$DateTime, format = "%d/%m/%Y %H:%M:%S") < Boundary,
                  "a holiday", "workday")
DF
#>              DateTime      Flag
#> 1 08/01/2022 08:15:34 a holiday
#> 2 10/01/2022 13:24:53   workday

#method with lubridate package
library(lubridate)
#> 
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#> 
#>     date, intersect, setdiff, union
DF <- data.frame(DateTime = c("08/01/2022 08:15:34", 
                              "10/01/2022 13:24:53"))

Boundary <- dmy_hms("10/01/2022 00:00:00")

DF$Flag <- ifelse(dmy_hms(DF$DateTime) < Boundary, "a holiday", "workday")

DF
#>              DateTime      Flag
#> 1 08/01/2022 08:15:34 a holiday
#> 2 10/01/2022 13:24:53   workday

Created on 2022-06-15 by the reprex package (v2.0.1)

1 Like

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.