For specifying the number of digits, use round(a, digits=2)
. However, you can also use sprintf
to deal with both the number of digits and the + or - in your equation: e.q. %+3.2f, where %
forces the + or - sign in the equation and 3.2f
controls the number of digits, so this solves both your issues. I found a solution for the superscript problem in sprintf
here: "B2 is the hex code for UTF-8 character = ^2 and \U is a control sequence that will call that character."
# data and regression
set.seed(1)
y = 1:10+rnorm(10)
x = 1:10
fit = lm(y~x)
b = coef(fit)[1]
a = coef(fit)[2]
r2 = summary(fit)$r.squared
# plot data and regression
plot(x, y)
abline(fit, col=2)
# add text to plot with legend() for convenient placement
legend('topleft', title='option 1', legend=sprintf("y = %3.2fx %+3.2f, R\UB2 = %3.2f", a, b, r2), bty='n', cex=0.7)
# if you prefer a pretty space between plus/minus and b:
if( b<0) {my_sign = ' - '; b = -b} else { my_sign= ' + '}
legend('bottomright', title='option 2', legend=sprintf("y = %3.2f x %s %3.2f, R\UB2 = %3.2f", a, my_sign, b, r2), bty='n', cex=0.7)