如何 select data.table 中未清理数据的年份范围?

How to select range of year in uncleaned data in data.table?

我的一些数据采用这种格式:

                     Year  Persons
1:                   2014       69
2:                   2013       76
3:     2013 couldn't come        3
4:                   2012       48
5:                   2011       57
6:                               1

如您所见,Year 列中的数据不干净。当我想要 select 年从 2011 年到 2014 年的行时,以下代码有效:

DF[Year %in% c("2014", "2013", "2012", "2011") ]

Select 年份范围:

DF[Year >= 2011 and Year <= 2014] # This won't filter out the row like `2013 couldn't come`.

如果我们 select 所有常规年份,(去掉带有其他文本的年份,以及空年份),我想我可以使用正则表达式:

DF[ Year == '[0-9]{4}',]    # doesn't work.

但是,它不起作用。如何在data.table中使用正则表达式?

  1. select 年份范围;
  2. 过滤掉不整洁的年份。

您可以提取年份:

DF[,Year:=as.numeric(gsub("([0-9]+).*","\1",Year))]

或者,如果您真的只想执行#1 和#2 而不是清理数据,则只需一个字符串操作:

dat[grepl("^201[1-4]$", Year)]