The following code does not work correctly inside knitr code chunk (it does not extract the desired substring):
What might be causing this behavior?
#Retrieve the earliest date
earlydate <- min(time(month[1]), "2016-04-20")
earlydate
#Extract YYYY-MM from earliest date
substr(earlydate, 1, 7)
where month[1] is
TSLA.Open TSLA.High TSLA.Low TSLA.Close TSLA.Volume TSLA.Adjusted
2016-02-16 158.7 162.95 154.11 155.17 5556300 155.17
#extracts the date:
time( month[1] )
2016-02-16
Expect to see the following in knitr output (R Markdown):
## [1] 2016-02
Instead actual output is not extracted, just show original text:
## [1] 2016-02-16
However either of the following does works correctly (extracts YYYY-MM):
#inline r code
`r substr("2016-02-16", 1,7)`
outputs: ## [1] 2016-04
#knitr code chunk
```{r test, message=FALSE, warning=FALSE}
earlydate <- "2016-02-16"
earlydate
#Extract YYYY-MM from earliest date
substr(earlydate, 1, 7)
```
outputs: ## [1] 2016-04
Class Details When both are arguments are type Date
#Retrieve the earliest date
earlydate <- min(time(month[1]), as.Date("2016-04-20"))
class(earlydate)
## [1] "Date"
When one is type date and the other type "character"
#Retrieve the earliest date
earlydate <- min(time(month[1]), "2016-04-20")
class(earlydate)
## [1] "Date"
Additional Info
Environment
OS: Win7
RStudio Version 0.99.892
Rx64 3.2.4 (R version)
document type: shiny knitr doc (.Rmd)
Library: quantmod
Library: knitr
The substr function does not appear to extract the substring in a shiny knitr Rmd document.
Details are in the following stackflow link:
Rscript - knitr: substr function not working correctly inside knitr code chunk
Minimal Reproducible Example (this does not extract desired substring):
substr( min( as.Date(2013-03-14), "2016-04-20"), 1,7)
outputs: ## [1] "2013-03-14"
Expect (this works as expected):
substr( min( as.Date(2013-03-14), as.Date("2016-04-20")), 1,7)
outputs (desired): ## [1] "2013-03"
It appears unrelated to knitr, since this behavior is also seen on the R console. Returned classes (as stated above) and data processing do not appear to correlate. It would appear to be an underlying R issue.
Is this WAD?
BR/KK