Home > front end >  How to use mutate ifelse gether date in r
How to use mutate ifelse gether date in r

Time:10-10

I want to use dplyr::mutate find gether date.

example I want to find data of EDS>2020-10-01 ,but my code is fail.

test1 <-  data %>%
   mutate(g = ifelse(  (EDS > "2020-10-01" & `price`>0 ) | 
              (is.na(EDS) & `price`>0 ) , 1 , 0))

What is the right way of coding this? Thanks!


Warning message: Problem while computing g = ifelse(...). ℹ Incompatible methods ("Ops.POSIXt", "Ops.Date") for ">"

CodePudding user response:

The column is POSIXlt class which is a list. Converting to Date class should work

library(dplyr)
data %>%
   mutate(EDS = as.Date(EDS), g = ifelse(  (EDS > "2020-10-01" & `price`>0 ) | 
              (is.na(EDS) & `price`>0 ) , 1 , 0))

Otherwise, the comparison with character class or Date class should have worked

> "2019-01-01" > "2020-01-01"
[1] FALSE
> "2019-01-01" > "1999-01-01"
[1] TRUE

data

data <- data.frame(EDS = c("1990-01-01", "2020-10-01", 
     "2021-10-01"), price = c(1.5, 0, 0.5))
  • Related