Avoid that ifelse Function Converts Date into Numeric in R (2 Examples)
In this R article you’ll learn how to avoid that the ifelse function converts date objects to the numeric class.
Example Data
x <- as.Date(c("2026-07-15", # Constructing vector of dates "2027-11-13", "2025-12-12")) x # [1] "2026-07-15" "2027-11-13" "2025-12-12" |
x <- as.Date(c("2026-07-15", # Constructing vector of dates "2027-11-13", "2025-12-12")) x # [1] "2026-07-15" "2027-11-13" "2025-12-12"
Example 1: ifelse() of Base R Turns Dates into Numeric
x1 <- ifelse(test = x == "2025-12-12", # Apply ifelse function yes = x + 1, no = x) x1 # [1] 20649 21135 20435 |
x1 <- ifelse(test = x == "2025-12-12", # Apply ifelse function yes = x + 1, no = x) x1 # [1] 20649 21135 20435
class(x1) # Testing the output class # [1] "numeric" |
class(x1) # Testing the output class # [1] "numeric"
Example 2: Prevent ifelse() from Turning Dates into Numeric Using if_else() Function of dplyr Package
install.packages("dplyr") # Install dplyr package library("dplyr") # Load dplyr |
install.packages("dplyr") # Install dplyr package library("dplyr") # Load dplyr
x2 <- if_else(condition = x == "2025-12-12", # Using if_else function of dplyr package true = x + 1, false = x) x2 # [1] "2026-07-15" "2027-11-13" "2025-12-13" |
x2 <- if_else(condition = x == "2025-12-12", # Using if_else function of dplyr package true = x + 1, false = x) x2 # [1] "2026-07-15" "2027-11-13" "2025-12-13"
class(x2) # Testing the output class # [1] "Date" |
class(x2) # Testing the output class # [1] "Date"