Search code examples
rrstan

Use a prior triangular distribution in rethinking - R


I’m using the rethinking package in R to make a simple linear model. In the folowing code I use a prior normal distribution for the dependent variable and everything works good.

library(rethinking)
col <- alist(
  courework_n ~ dnorm(mean,0.2),
  mean <- a + b*result_n + c,
  a ~ dnorm(0,10),
  b ~ dnorm(0,10),
  c ~ dnorm(0,10)
)
colmap <- map( col , data.frame(data) )

But when I use a package for triangular distribution which is not supported directly by R, I get the following error

Error in map(col, data.frame(data)) : unused argument (log = TRUE)

This is the code for defining the model with the triangle distribution

install.packages("RTriangle") 
library(triangle)

col <- alist(
  courework_n ~ dtriangle(0,1,mode),
  moda <- a + b*result_n + c,
  a ~ dnorm(0,10),
  b ~ dnorm(0,10),
  c ~ dnorm(0,10)
)

col_map <- map( col , data.frame(data) )

Solution

  • Because the dtriangle distribution doesn't incorporate a log parameter as is expected of probability distribution functions in R/by rethinking.

    You can hack the dtriangle function as follows:

    • first dput(dtriangle,file="my_dtriangle.R") to save the function code to a file
    • edit the first line to read
     my_dtriangle <- function (x, a = 0, b = 1, c = (a + b)/2, log=FALSE)
    
    • change the last line of code (return(apply(params, 1, dTest))) to:
     res <- apply(params, 1, dTest)
     if (log) return(log(res)) else return(res)
    
    • source("my_dtriangle.R") to redefine the function in your workspace

    It's conceivable that you will run into further technical problems using a function that has compact support (i.e., has zero likelihood outside of a restricted range of values)