How to determine if date is a weekend or not (not using lubridate)

You can use the base R function weekdays(). x <- seq(Sys.Date() – 10, Sys.Date(), by = 1) weekdays(x, abbr = TRUE) # [1] “Wed” “Thu” “Fri” “Sat” “Sun” “Mon” “Tue” “Wed” “Thu” “Fri” “Sat” x[grepl(“S(at|un)”, weekdays(x))] # [1] “2014-10-11” “2014-10-12” “2014-10-18” As far as lubridate goes, wday() has a label argument. When set to TRUE, … Read more

Add (subtract) months without exceeding the last day of the new month

The lubridate function %m+% may be useful here: Add and subtract months to a date without exceeding the last day of the new month as.Date(“2014-12-31”) %m+% months(6) # [1] “2015-06-30” To also handle the second case, you will need to round up to nearest month using ceiling_date, and subtract one day using days. ceiling_date(as.Date(“2014-02-28”) %m+% … Read more

How to extract Month from date in R

?month states: Date-time must be a POSIXct, POSIXlt, Date, Period, chron, yearmon, yearqtr, zoo, zooreg, timeDate, xts, its, ti, jul, timeSeries, and fts objects. Your object is a factor, not even a character vector (presumably because of stringsAsFactors = TRUE). You have to convert your vector to some datetime class, for instance to POSIXlt: library(lubridate) … Read more

How to aggregate a dataframe by week?

In the tidyverse, df2 %>% group_by(week = week(time)) %>% summarise(value = mean(values)) ## # A tibble: 5 × 2 ## week value ## <dbl> <dbl> ## 1 8 37.50000 ## 2 9 38.57143 ## 3 10 38.57143 ## 4 11 36.42857 ## 5 12 45.00000 Or use isoweek instead: df2 %>% group_by(week = isoweek(time)) %>% … Read more