Bob - 3 months ago 10

R Question

I'm trying to make the legend of this plot pretty, so I need there the be an actual superscript, which is why I am using the pretty10exp() function from the sfsmisc library. It works when I use the c() function.

However, I am also trying to keep the string and the scientific notation number on the same line. The legend() is broken into two lines, which I think is due to c(). I thought I could use paste(), but for some reason the output is now incorrect.

`plot(1:12)`

pVal <- 4

legend("topright", legend = c("P value:", sfsmisc::pretty10exp(pVal)), cex = 1.5)

legend("topright", legend = paste("P value:", sfsmisc::pretty10exp(pVal)), cex = 1.5)

pVal being an arbitrary number represented in scientific notation. The second line results in output like this:

`"P value: (significand) %*% 10^-4"`

Answer

`pretty10exp`

returns an expression which allows it to use the `?plotmath`

features for making nice looking numbers. When working with expressions, you can't just paste values in like strings. You need to manipulate them with a special set of functions. One such function is `substitute`

. You can do

```
plot(1:12)
pVal <- 4
legend("topright", cex = 1.5,
legend = substitute("P value: "*x, list(x=sfsmisc::pretty10exp(pVal)[[1]])) )
```

We use `substitute()`

to take the value contained in the expression from `pretty10exp`

and prefix it with the label you want. (We use `*`

to concatenate rather than `paste()`

since `plotmath`

allows it)

Source (Stackoverflow)

Comments