r - bquote: How to include an expression saved as a string object? -


my goal annotate plot slope of best-fit line , label units of slope, label saved separate string object. i'm having trouble figuring out how bquote() convert string object expression, , combine other evaluated statements.

a demonstration:

# example data: x <- c(1:20)                   # x units: time y <-  x * rnorm(20, 10, 2)     # y units: length per time  unit.label <- "l%.%t^-2"       # label slope of best fit line  lm1 <- summary(lm(y ~ x))  plot(y ~ x) 

the problem occurs when try annotate plot. can bquote() display slope:

text(median(x), min(y), bquote(slope: .(round(lm1$coefficients[2], 2))) ) 

i can bquote() show slope's units:

plot(y ~ x) text(median(x), min(y), bquote(.(parse(text = unit.label))) ) 

but i'm unable combine label , slope single bquote() statement:

plot(y ~ x) text(median(x), min(y), bquote(slope: .(round(lm1$coefficients[2], 2))  .(parse(text = unit.label))) )  # error: unexpected symbol in "text(median(x), min(y), bquote(slope:  # .(round(lm1$coefficients[2], 2)) ." 

using paste(), unit label appears along slope, label isn't read expression:

plot(y ~ x) text(median(x), min(y), bquote(slope: .(paste(round(lm1$coefficients[2], 2),  as.expression(unit.label)))) ) 

where going wrong? simple syntax problem in bquote command? suggestions!

1) parse char string create character string desired (ensuring represents expressoin syntactically valid in r) , parse it. here main_s character string:

fm <- lm(y ~ x)  main_s <- paste("slope:", round(coef(fm)[2], 2), "~", unit.label) plot(0, main = parse(text = main_s)) 

the statement setting main_s alternately replaced following sprintf statement arguably more readable:

main_s <- sprintf("slope: %.2f ~ %s", coef(fm)[2], unit.label) 

2) bquote above straight-forward way handle use bquote try unit.label_c call object , fm defined above:

unit.label_c <- parse(text = unit.label)[[1]] plot(0, main = bquote(slope: .(round(coef(fm)[2], 2)) ~ .(unit.label_c))) 

in either case this:

screenshot

upodate added (2). improvements , corrections.


Comments

Popular posts from this blog

database - VFP Grid + SQL server 2008 - grid not showing correctly -

jquery - Set jPicker field to empty value -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -