rexpressionlegendcbind

Use expression() inside a matrix to create a legend in R


In an experiment I am running, the plot legend is created as follows:

eigenvalues <- t(c(1,2))
plot(1)
# Legend
legend_text <- cbind(
  paste("λ1 =", eigenvalues[, 1]),
  paste("λ2 =", eigenvalues[, 2])
)
legend("topright", legend = legend_text, text.col = "black", bty = "n", cex = 1)

enter image description here

However, instead of "λ1 =" I would like to use lambda[1], but when I use it I get the following error:

legend_text <- cbind(
  expression(lambda[1] == eigenvalues[, 1]),
  expression(lambda[2] == eigenvalues[, 2])
)

Error in cbind(expression(lambda[1] == eigenvalues[, 1]), expression(lambda[2] ==  : 
  cannot create a matrix from type 'expression'

How do I use expression(lambda[1] for the legend without getting an error message?


Solution

  • In order to use plotmath parsing, you need to provide expressions:

    legend_text <- lapply(1:2, \(j) bquote(lambda[.(i)] == .(e), 
                                           list(i = j, e = eigenvalues[, j])))