[英]Subsetting data.table set by date range in R
I have a large dataset in data.table that I'd like to subset by a date range. 我在data.table中有一个大型数据集,我想按日期范围进行分组。 My data set looks like this:
我的数据集如下所示:
testset <- data.table(date=as.Date(c("2013-07-02","2013-08-03","2013-09-04",
"2013-10-05","2013-11-06")),
yr = c(2013,2013,2013,2013,2013),
mo = c(07,08,09,10,11),
da = c(02,03,04,05,06),
plant = LETTERS[1:5],
product = as.factor(letters[26:22]),
rating = runif(25))
I'd like to be able to choose a date range directly from the as.Date
column without using the yr
, mo
, or da
columns. 我希望能够直接从
as.Date
列中选择日期范围,而不使用yr
, mo
或da
列。 Currently, I'm subsetting by mo
and it's extremely clunky at times, especially when years switch over. 目前,我是
mo
子集,有时非常笨重,尤其是在多年转换的时候。 A more elegant method of doing this would make my life infinitely easier. 一种更优雅的方法可以让我的生活变得更加轻松。
Thanks in advance! 提前致谢!
为什么不:
testset[date>="2013-08-02" & date<="2013-11-01"]
See also: 也可以看看:
?`%between%`
Works like this: 像这样工作:
testset[date %between% c("2013-08-02", "2013-11-01")]
You mentioned that you are subsetting, but its not clear whether you are using the subset fn in R. 你提到你是子集,但不清楚你是否在R中使用子集fn。
Type ?subset into the R console to see the details of the subset() function in R which 'returns a subset of vectors, matrices or data frames which meet conditions'. 在R控制台中键入?子集以查看R中的subset()函数的详细信息,其中'返回满足条件的向量,矩阵或数据帧的子集'。 Then use part of the method that Troy posted above to choose the date range
然后使用Troy上面发布的方法的一部分来选择日期范围
thisYear <- subset(testset, date > "2015-01-01" & date < "2015-12-31")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.