Search code examples
rif-statementdummy-variable

Error in filtering by date in R: object of type 'closure' is not subsettable


I want to create a new variable in my data table in R that will be equal to 1, if the date of the event is after a certain time (2019-01-01) and will be equal to 0 otherwise. I am using the following code:

dt$time <- ifelse[dt$date > '2019-01-01',1,0]

But I am getting a mistake:

object of type 'closure' is not subsettable.

To be honest, I don't understand what is wrong.


Solution

  • You are using wrong syntax, you probably meant :

    dt$time <- ifelse(dt$date > '2019-01-01',1,0)
    

    Even if the above work it will not give you correct output always because you are comparing date with string here (check class('2019-01-01')). You should probably use

    dt$time <- ifelse(dt$date > as.Date('2019-01-01'), 1, 0)
    

    but you don't really need ifelse here, you can convert the logical values after comparison to integer values.

    dt$time <- as.integer(dt$date > as.Date('2019-01-01'))
    #OR
    #dt$time <- +(dt$date > as.Date('2019-01-01'))