Exclude specific time periods in R

ぐ巨炮叔叔 提交于 2019-11-29 04:43:20
csgillespie

You seem to know the basic idea, but are just missing the details. As you mentioned, we just transform the Timestamps into POSIX objects then subset.

lubridate Solution

The easiest way is probably with lubridate. First load the package:

library(lubridate)

Next convert the timestamp:

##*m*onth *d*ay *y*ear _ *h*our *m*inute
d = mdy_hm(dd$Timestamp)

Then we select what we want. In this case, I want any dates after 7:30pm (regardless of day):

dd[hour(d) == 19 & minute(d) > 30 | hour(d) >= 20,]

Base R solution

First create an upper limit:

lower = strptime("2/14/2011 19:30","%m/%d/%Y %H:%M")

Next transform the Timestamps in POSIX objects:

d = strptime(dd$Timestamp, "%m/%d/%Y %H:%M")

Finally, a bit of dataframe subsetting:

dd[format(d,"%H:%M") > format(lower,"%H:%M"),]

Thanks to plannapus for this last part


Data for the above example:

dd = read.table(textConnection('Timestamp Temp.Diff
"2/14/2011 19:00" -0.385
"2/14/2011 19:10" -0.535
"2/14/2011 19:20" -0.484
"2/14/2011 19:30" -0.409
"2/14/2011 19:40" -0.385
"2/14/2011 19:50" -0.215'), header=TRUE)

You can do this with easily with the time-based subsetting in the xts package. Assuming your data.frame is named Data:

library(xts)
x <- xts(Data$Temp.Diff, Data$Timestamp)
y <- x["T12:00/T15:00"]
# you need the leading zero if the hour is a single digit
z <- x["T09:00/T12:00"]
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!