0

I want the dates of a given weekday (let´s say Fridays) between this two dates:

selectedMonths <- c(  "201002",
                      "201103"
                    ) 

How can I store them in a data.frame, the desire results is:

    Date
2010-02-05
2010-02-12
2010-02-19
...
2011-03-04
2011-03-11
2011-03-18
2011-03-25

I want to include the Fridays of the last date "201103

LuisMoncayo
  • 125
  • 2
  • 9
  • 1
    Possible duplicate of [Get Dates of a Certain Weekday from a Year in R](http://stackoverflow.com/questions/9166437/get-dates-of-a-certain-weekday-from-a-year-in-r). Also related: [generate dataframe of Friday dates for the year](http://stackoverflow.com/questions/20671139/r-generate-dataframe-of-friday-dates-for-the-year) – Jota Mar 22 '16 at 18:45
  • Not exactly, given I want the dates of a week day between two months of different years, not the whole year – LuisMoncayo Mar 23 '16 at 00:39
  • I look at the answers to those questions, and I see how to answer your question. In the first link, Kyle Brandt offered this answer, which you can adapt: `x = seq(as.Date("2012/01/02"), as.Date("2013/01/01"), "7 days")`. In the second link, thelatemail wrote a function `pick.wkday` which you should be able to use. Make sure to look through all the answers & Good Luck! – Jota Mar 23 '16 at 00:45
  • Sorry for insists but with those answers I cannot solve my problem given my data selectedMonths <- c( "201002", "201103"). I want the result posted in my question – LuisMoncayo Mar 23 '16 at 00:51
  • dates <- seq.Date(as.Date(startdates[1]),as.Date(end),by="1 day") dates[weekdays(dates)==dayName] allRelatedDates<-data.frame(dates[format(dates,"%w")==5]) colnames(allRelatedDates) <- c("SelectedDates") dim(allRelatedDates) – LuisMoncayo Mar 23 '16 at 01:12
  • Format your dates, then apply a solution. For instance, `dates <- as.Date(paste0(selectedMonths, "01"), format = "%Y%m%d"); pick.wkday(5, dates[1], dates[2])` – Jota Mar 23 '16 at 01:12

1 Answers1

1

Here is one approach using lubridate and dplyr

library(lubridate)
library(dplyr)

startdates <- ymd(paste0(selectedMonths, "01"))

df <- data.frame(dates = seq(startdates[1], startdates[2], by = "day"))

df %>%
  mutate(weekday = weekdays(dates)) %>%
  filter(weekday == "Friday")
cdeterman
  • 19,630
  • 7
  • 76
  • 100
  • My solution based on yours: startdates <- ymd(paste0(selectedMonths, "01")) df <- data.frame(dates = seq(startdates[1], startdates[1] + months(1) - days(1), by = "day")) filterDates <- df %>% mutate(weekday = weekdays(dates)) %>% filter(weekday == "Sunday") filterDates[,1] – LuisMoncayo Mar 23 '16 at 15:47