[R] How to format R superscript 2 followed by "=" value
Joshua Wiley
jwiley.psych at gmail.com
Mon Oct 3 07:39:19 CEST 2011
Hi Nevil,
Here is one option:
################################
## function definition
r2format <- function(object, digits = 3, output, sub, expression = TRUE, ...) {
if (inherits(object, "lm")) {
x <- summary(object)
} else if (inherits(object, "summary.lm")) {
x <- object
} else stop("object is an unmanageable class")
out <- format(x$r.squared, digits = digits)
if (!missing(output)) {
output <- gsub(sub, out, output)
} else {
output <- out
}
if (expression) {
output <- parse(text = output)
}
return(output)
}
## model
m <- lm(mpg ~ hp * wt, data = mtcars)
## demonstration
r2format(object = m, output = "R^2 == rval", sub = "rval", expression = TRUE)
## your problem
x <- runif(10)
y <- runif(10)
mylm <- lm(y ~ x)
plot(x, y)
abline(mylm)
## simplified version of demo
mtext(r2format(m, 3, "R^2 == rval", "rval"), 3)
################################
The real key is using == instead of "=". The lengthy response is
because I have been toying with and working with different stylers and
formatters to try to facilitate getting output from R into publication
format so I was interested in playing with this and thinking what
might be useful abstractions. Anyway, more specific to your useage
might be something like:
substitute(expression(R^2 == rval), list(rval =
round(summary(mylm)$r.squared,3)))
Cheers,
Josh
On Sun, Oct 2, 2011 at 9:49 PM, Nevil Amos <nevil.amos at gmail.com> wrote:
> I am trying to put an
> R2 value with R2 formatted with a superscript 2 followed by "=" and the
> value :
> the first mtext prints the R2 correctly formatted but follows it with
> "=round(summary(mylm)$r.squared,3)))" as text
> the second prints "R^2 =" followed by the value of
> round(summary(mylm)$r.squared,3))).
>
> how do I correctly write the expression to get formatted r2 followed by the
> value?
>
>
>
>
> x=runif(10)
> y=runif(10)
> summary(mylm<-lm(y~x))
> plot(x,y)
> abline(mylm)
> mtext(expression(paste(R^2,"=",round(summary(mylm)$r.squared,3))),1)
> mtext(paste(expression(R^2),"=",round(summary(mylm)$r.squared,3)),3)
>
>
>
> thanks
>
> Nevil Amos
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
--
Joshua Wiley
Ph.D. Student, Health Psychology
Programmer Analyst II, ATS Statistical Consulting Group
University of California, Los Angeles
https://joshuawiley.com/
More information about the R-help
mailing list