问题
I have a dataset consisting of two columns. A datetime column and a column with numerical values. Its a simple dataset, so I did not attach it..
What I need to do, is to filter or subset the data corresponding with a class schedule, so that I get a dataset/dataframe with datetime values and numerical values for the time when the class has lectures only.
The class schedule is different from each day of the week, e.g. Mondays 8:00-9.50, 10.30-11.30, 14.50-15:50. Tuesdays 10.30-11.30, 14.10-15.30, Wednesdays...an so on.
Any idea how I could do this?
I usually convert datetime-values to POSIXct format, but recently I read about lubridate.
I am just still not sure how to efficiently subset with all these criteria.
Perhaps I should subset the data according to the weekdays first. And then subset the different weekdays according to the lecture time...
Hope someone can help me.
BTW: The data is for all of 2014, so I actually have to avoid the data when the class have holidays as well...
回答1:
Convert class intervals to an interval
class in lubridate
. Then subset based on the test of if the dates are in the intervals...
> a <- new_interval(Sys.time(), Sys.time() + 120)
> Sys.time() %within% a
[1] TRUE
回答2:
I will try this, where the D$Time is in POSIXct format:
# Create column with weekday
D$Weekday <- D$Time
D$Weekday <- weekdays(as.Date(D$Time))
# Subset weekdays
MO <- subset(D, D$Weekday == "Monday")
head(MO)
TU <- subset(D, D$Weekday == "Tuesday")
WE <- subset(D, D$Weekday == "Wednesday")
MO <- subset(D, D$Weekday == "Thursday")
MO <- subset(D, D$Weekday == "Friday")
MO <- subset(D, D$Weekday == "Saturday")
# Subset lecture of weekday
MO_L1 <- subset(MO, format(MO$Time, "%H:%M:$S") > "07:55:00" &
format(MO$Time, "%H:%M:$S") < "09:30:00")
head(MO_L1)
tail(MO_L1)
MO_L2 <- subset(MO, format(MO$Time, "%H:%M:$S") > "10:55:00" &
format(MO$Time, "%H:%M:$S") < "11:30:00")
And in the end combine all the subset to a new dataset...
来源:https://stackoverflow.com/questions/30516157/how-to-filter-or-subset-specific-date-and-time-intervals-in-r-lubridate