Here is a simple user-defined function:
functions{
real minpdf( real z, real[,] v){
real result;
for (j in 1:4) {
if (z <= v[j + 1, 1]){
result = v[j, 2] +
(v[j + 1,2]-v[j, 2]) * (z-v[j, 1]) / (v[j + 1, 1]-v[j, 1]);
break;
}
}
return(result);
}
}
Using Rstudio I click on Save with Click on save activated. All goes well:
rstan:::rstudio_stanc("stantest2.stan")
stantest2.stan is syntactically correct.
But if I put the same code into an Rmarkdown document such as this:
---
title: "stantest"
author: "Jeremy Colman"
date: "`r Sys.Date()`"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(cmdstanr)
register_knitr_engine(override = FALSE)
functions{
real minpdf( real z, real[,] v){
real result;
for (j in 1:4) {
if (z <= v[j + 1, 1]){
result = v[j, 2] +
(v[j + 1,2]-v[j, 2]) * (z-v[j, 1]) / (v[j + 1, 1]-v[j, 1]);
break;
}
}
return(result);
}
}
and then click on Knit it all goes wrong:
Syntax error in '/var/folders/fx/8zjr0h4d789bdxlr_ptj66jw0000gs/T/RtmpQjp6RG/model-1eaed49f4f4.stan', line 3, column 27 to column 28, parsing error:
-------------------------------------------------
1: functions{
2:
3: real minpdf( real z, real[,] v){
^
4: real result;
5: for (j in 1:4) {
-------------------------------------------------
An identifier is expected as a function argument name.
make: *** [/var/folders/fx/8zjr0h4d789bdxlr_ptj66jw0000gs/T/RtmpQjp6RG/model-1eaed49f4f4.hpp] Error 1
Quitting from lines 19-34 [unnamed-chunk-2] (stantest.Rmd)
Execution halted
Is there an error in my code or not? If there is, why does it not show up in the first test? And if there is an error what is it?
Grateful for any help.