Select subset by date in R

11,342

Solution 1

If you're willing to use another package (lubridate), this should work. Among other things, Lubridate parses dates. just put use ymd('datestring') where y is year, m is month and d is days in the order they occur in the string you're trying to parse.

> df
  n_child sex  date_born
1       1   M 20/03/2002
2       2   M 09/03/2001
3       3   F 01/09/2003
4       4   M 07/05/2003
5       5   M 12/09/2004
6       6   F 19/08/2004

> require(lubridate)
> df$dateborn <- dmy(df$date_born)
6 parsed with %d/%m/%Y
> datesub <- df[df$date_born < ymd(20040101),]
1 parsed with %Y%m%d

> datesub
  n_child sex  date_born
1       1   M 2002-03-20
2       2   M 2001-03-09
3       3   F 2003-09-01
4       4   M 2003-05-07

Solution 2

alternatively:

n.child<-as.numeric(c(1,2,3,4,5,6))
sex<-as.factor(c("f","f","f","m","m","f"))
date_born<-as.Date(c("2002-01-01", "2002-12-01", "2003-05-13", "2003-06-17", "2004-01-03", "2004-09-09"))
DF<-data.frame(n.child, sex,date_born)


DF1<-DF[DF$date_born<"2004-01-01",]


> DF1
  n.child sex  date_born
1       1   f 2002-01-01
2       2   f 2002-12-01
3       3   f 2003-05-13
4       4   m 2003-06-17
Share:
11,342
Cris
Author by

Cris

Updated on July 23, 2022

Comments

  • Cris
    Cris almost 2 years

    I have a file and I need to select just children that were born before the year 2004.

    Example

    n_child     sex   date_born
         1        M  20/03/2002
         2        M  09/08/2001
         3        F  01/09/2003
         4        M  07/05/2003
         5        M  12/09/2004
         6        F  19/08/2004
    

    I want

    n_child     sex   date_born
         1        M  20/03/2002
         2        M  09/08/2001
         3        F  01/09/2003
         4        M  07/05/2003
    

    I tried the following, but it did not work:

    datesub <- (as.POSIXlt(df$date_born)$year)<2004
    dat     <- df[datesub, ]