Priyank Puri
Priyank Puri

Reputation: 75

R Markdown: Set Start of the week date in parameters

I am trying to set my Markdown parameter to the first day of the week. I tried executing the following code but there seems to be an error with date conversion. Below is the markdown code.

---
title: "Sample Markdown"
author: "ABC"
date: "`r format(Sys.time(), '%d %B, %Y')`"
tables: yes
output: html_document
params:
  dts: 
    label: "Start Date"
    input: date
    value: !r as.Date(round(as.IDate(as.character(Sys.Date()), "%m-%d-%Y"), "week")-1)
    max: !r Sys.Date()
  dte: 
    label: "End Date"
    input: date
    value: !r Sys.Date()-1
    max: !r Sys.Date()

---

```{r setup, include=TRUE,echo=FALSE,message=FALSE}
knitr::opts_chunk$set(echo = TRUE)
options(java.parameters = "-Xmx32000m")
dt_start=as.character(as.Date(params$dts))
dt_end=as.character(as.Date(params$dte))

print(dt_start)
print(dt_end)
```

Upvotes: 2

Views: 1009

Answers (1)

Andrew Chisholm
Andrew Chisholm

Reputation: 6567

The lubridate package has some nice functions for this. Here's an example using floor_date.

---
title: "Sample Markdown"
author: "ABC"
date: "`r format(Sys.time(), '%d %B, %Y')`"
tables: yes
output: html_document
params:
  dts: 
    label: "Start Date"
    input: date
    value: !r lubridate::floor_date(Sys.Date(), 'week')
    max: !r Sys.Date()
  dte: 
    label: "End Date"
    input: date
    value: !r Sys.Date()-1
    max: !r Sys.Date()
---

```{r setup, include=TRUE,echo=FALSE,message=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(lubridate)
options(java.parameters = "-Xmx8000m")
dt_start=params$dts
dt_end=params$dte

print(dt_start)
print(dt_end)
```

Upvotes: 1

Related Questions