在R中按日期选择子集 [英] Select subset by date in R

查看:120
本文介绍了在R中按日期选择子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件,我只需要选择2004年之前出生的孩子。

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

示例

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

我要

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, ]


推荐答案

如果您愿意使用其他软件包(lubridate),则应该可以使用。除其他外,Lubridate解析日期。只需使用 ymd('datestring')即可,其中y是年,m是月,d是天(按它们在您尝试解析的字符串中出现的顺序)。

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

这篇关于在R中按日期选择子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆