Skip to content

Commit

Permalink
add difftime() example
Browse files Browse the repository at this point in the history
fix bug in solution to thanksgiving problem
  • Loading branch information
gregridgeway committed Sep 18, 2018
1 parent b5c684f commit 6cd5052
Show file tree
Hide file tree
Showing 2 changed files with 110 additions and 93 deletions.
10 changes: 8 additions & 2 deletions 02 Dates and times.Rmd
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,12 @@ b-mdy("12/01/2014")
date(now())-b
```

When subtracting dates, R will make a good guess for the unit of time to use in the result. Use `difftime()` if you want to be specific about the unit of time and not leave it up to R to decide.
```{r comment="", results='hold'}
difftime(b, mdy("12/01/2014"), units = "days")
difftime(b, mdy("12/01/2014"), units = "hours")
```

We can add time to the dates as well
```{r comment="", results='hold'}
b + dyears(1) # adds 365 days, does not increase year by 1
Expand Down Expand Up @@ -175,15 +181,15 @@ a[min(which(tzone=="CST"))]
2. On what date will Thanksgiving fall in 2020?
```{r comment="", results='hold'}
a <- mdy(paste0("11/",1:30,"/2020"))
a[wday(a,label=TRUE)=="Thurs"][4]
a[wday(a,label=TRUE)=="Thu"][4]
```

3. Make a function that takes as input a year and returns the date of Thanksgiving in that year.
```{r comment="", results='hold'}
tday <- function(year)
{
a <- mdy(paste0("11/",1:30,"/",year))
return( a[wday(a,label=TRUE)=="Thurs"][4] )
return( a[wday(a,label=TRUE)=="Thu"][4] )
}
tday(2020)
lapply(2020:2100, tday)
Expand Down
Loading

0 comments on commit 6cd5052

Please sign in to comment.