如何将 ifelse 与日期一起使用

How to use ifelse with dates

我在 R 中的日期格式为 01/01/2000

我想创建一个包含类别的列,将我的主题分类为 01/02/2001 ==1 之前或 02/02/2001 ==2 之后的出生日期。这会用 ifelse 来完成吗?

你会怎么表达?

谢谢

这取决于格式,您必须添加函数“as.Date()

例如:

dates <- c("01-02-2001", "30-01-2001", "15-05-2001", "08-10-1992","08-09-2020")

adates=as.Date(dates, "%d-%m-%Y")

ifelse(adates>as.Date("01-02-2001","%d-%m-%Y"),1,0)

选项 1:ifelse()

ifelse(as.Date(date, "%d/%m/%Y") < as.Date("2001-02-02"), 1, 2)
# [1] 1 2 2 2

选项 2

2 - (as.Date(date, "%d/%m/%Y") < as.Date("2001-02-02"))
# [1] 1 2 2 2

选项 3:findInterval()

findInterval(as.Date(date, "%d/%m/%Y"), as.Date("2001-02-02")) + 1
# [1] 1 2 2 2

数据

date <- c("01/02/2001", "02/02/2001", "03/02/2001", "04/02/2001")