0

I have dates in R in format 01/01/2000

I want to create a column with a category that categorizes my subjects as date of birth before the 01/02/2001 ==1 or after 02/02/2001 ==2. Would this be done with an ifelse?

How would you express this?

Thanks

2
  • Do you want to extract the day in each date? Commented Sep 8, 2020 at 18:21
  • I want to have a column df$date_category with two factors (1== before and 2== after) in which I categorise the dates from the column df$date using a cutoff of 01/02/2001, so dates before first february 2001 get a 1 and those after get a 2. Commented Sep 8, 2020 at 18:28

2 Answers 2

1

Option 1 : ifelse()

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

Option 2

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

Option 3 : findInterval()

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

Data

date <- c("01/02/2001", "02/02/2001", "03/02/2001", "04/02/2001")
Sign up to request clarification or add additional context in comments.

Comments

0

it depends of the formats and you have to add the function "as.Date()

for example :

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.