There are two problems here. First, this is handled using ?plotmath in R. The operator you are looking for is bar() . This is not a function, but the markup that plotmath understands.
Secondly, you need an expression in which avg converted to its value. You need an expression because this is what plotmath works plotmath . There are several solutions to this problem, but I am using bquote() below. You provide it with an expression, and everything that is wrapped in .( ) Transforms its value, evaluating the subject inside .( ) .
Here is your code and the correspondingly modified legend() call:
test <- c(10,20,40,80,80) avg <- mean(test) avg <- format(avg,digits=2) plot(test, xlab="x", ylab="y", pch = 4) legend("topleft", legend = bquote(bar(x)*":" ~ .(avg)))
Note that this accurately inserts what is in avg . You may need
avg <- round(avg)
or another formatting fix to get something nice and presentable.
source share