【问题标题】:Can I subset specific years and months directly from POSIXct datetimes?我可以直接从 POSIXct 日期时间子集特定年份和月份吗?
【发布时间】: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)

我可以先创建YearMonth 列并将它们用于子集:

# 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 日期时间执行此操作(无需先创建 YearMonth 列。有什么想法吗?

【问题讨论】:

  • 您可以使用来自 base 的 months,但 AFAIK 年没有内置功能。 lubridate 包同时具有 yearmonth,然后是 test[month(test$DateTime) %in% c(4, 5), ] 之类的子集
  • 转换为数字然后与字符进行比较似乎有点愚蠢,你不觉得吗?

标签: r


【解决方案1】:
sub1 <- subset(test, format(DateTime, "%Y") %in% c("1983" , "1985")  )
sub2 <- subset(test, as.numeric(format(DateTime, "%m")) %in% 4:5)

【讨论】:

    猜你喜欢
    • 2017-01-19
    • 2018-10-15
    • 1970-01-01
    • 2013-02-15
    • 2013-09-23
    • 1970-01-01
    • 2023-03-20
    • 2021-12-28
    • 2015-03-27
    相关资源
    最近更新 更多