【发布时间】:2014-05-24 23:42:24
【问题描述】:
我有时间序列数据,我正在尝试对以下内容进行子集化:
1) 特定年份之间的时间段(从 1 月 1 日上午 12 点开始,到 12 月 31 日晚上 11 点结束) 2) 没有特定月份的时期
这是我正在尝试做的两个独立子集。
给定以下数据框:
test <- data.frame(seq(from = as.POSIXct("1983-03-09 01:00"), to = as.POSIXct("1985-01-08 00:00"), by = "hour"))
colnames(test) <- "DateTime"
test$Value<-sample(0:100,16104,rep=TRUE)
我可以先创建Year 和Month 列并将它们用于子集:
# Add year column
test$Year <- as.numeric(format(test$DateTime, "%Y"))
# Add month column
test$Month <- as.numeric(format(test$DateTime, "%m"))
# Subset specific year (1984 in this case)
sub1 = subset(test, Year!="1983" & Year!="1985")
# Subset specific months (April and May in this case)
sub2 = subset(test, Month=="4" | Month=="5")
但是,我想知道是否有更好的方法可以直接从 POSIXct 日期时间执行此操作(无需先创建 Year 和 Month 列。有什么想法吗?
【问题讨论】:
-
您可以使用来自 base 的
months,但 AFAIK 年没有内置功能。lubridate包同时具有year和month,然后是test[month(test$DateTime) %in% c(4, 5), ]之类的子集 -
转换为数字然后与字符进行比较似乎有点愚蠢,你不觉得吗?
标签: r