Anya Pilipentseva
Anya Pilipentseva

Reputation: 187

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.

Upvotes: 0

Views: 417

Answers (2)

alvaropr
alvaropr

Reputation: 799

The base::ifelse messes with variable formats. Be careful when using it. There is an alternative within dplyr package:

initial.date <- as.Date('2019-01-01')
dt$time <- dplyr::if_else(
    condition = dt$date > initial.date,
    true = 1,
    false = 0
)

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 389175

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'))

Upvotes: 2

Related Questions