In R, comments are preceded by the symbol #. Moreover, to avoid messing with the indentation, it's usually ## instead of #. Therefore, as I want to include some R code in a LaTeX document, I am using the listings package with these instructions. However, this gives me the following error:

Illegal parameter number in definition of \lst@rangebegin

Here is the R code:

GetObsLogLik <- function(data, w, mu, sigma){
  N <- nrow(data)
  S <- ncol(data)
  K <- nrow(mu)
  sum(sapply(1:N, function(i){
    log(sum(sapply(1:K, function(k){
      w[k] * dmvnorm(x=data[i,], mean=mu[k,],
                     sigma=sigma[k]^2 * diag(S))

And here is the LaTeX code:






The error disappears when I replace ## by //. But this is not a solution as // are not valid in R. I also tried the solution provided here but it doesn't work either.


1 Answer 1


The problem isn’t the R source code, it’s the fact that you are using special characters (#) in the \lstset options. Try using \#\# instead.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .