在 R 中按日期过滤时出错:'closure' 类型的对象不可子集化

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

我想在 R 中的数据 table 中创建一个新变量,如果事件的日期在某个时间 (2019-01-01) 之后,它将等于 1否则等于 0。我正在使用以下代码:

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

但我犯了一个错误:

object of type 'closure' is not subsettable.

老实说,我不明白哪里出了问题。

您使用了错误的语法,您的意思可能是:

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

即使上述工作正常,它也不会始终为您提供正确的输出,因为您在此处将日期与字符串进行比较(检查 class('2019-01-01'))。你可能应该使用

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

不过这里其实不需要ifelse,可以将比较后的逻辑值转换为整数值。

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

base::ifelse 乱用变量格式。使用时要小心。 dplyr 包中有一个替代方案:

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