Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert string into math expression in R?

Tags:

string

math

plot

r

I have a vectors of strings, say c("E^A","S^P","lambda","T","E^Q","E^Q","AT"), and I want to plot them as the x axis label using math expression. (I believe I have written them in math expression format, but with quote)

When I put

text(x,par("usr")[3]-0.2,labels=substitute(A,list(A=label)),srt=20,pos=1,adj = c(1.1,1.1), xpd = TRUE,cex=0.7)

The x axis only shows "E^A","S^P","lambda","T","E^Q","E^Q","AT", not the mathematical interpretation of the strings, and I guess it's because they are not regarded as math symbols.

How can I get mathematical labeling then? Thanks so much!

like image 795
Pengyao Avatar asked Apr 02 '12 04:04

Pengyao


People also ask

How do I convert a string to an expression in R?

Convert a String to an Expression in R Programming – parse() Function. parse() function in R Language is used to convert an object of character class to an object of expression class.

How do you write math equations in R?

Math inside RMarkdownIn side a text chunk, you can use mathematical notation if you surround it by dollar signs $ for “inline mathematics” and $$ for “displayed equations”. Do not leave a space between the $ and your mathematical notation. Example: $\sum_{n=1}^{10} n^2$ is rendered as ∑10n=1n2.

How do you convert a string to an expression in Python?

You can use the built-in Python eval() to dynamically evaluate expressions from a string-based or compiled-code-based input. If you pass in a string to eval() , then the function parses it, compiles it to bytecode, and evaluates it as a Python expression.


1 Answers

In general, use expression (see ?plotMath):

plot(1,main=expression(E^A))

Note that the 'E^A' is not in quote marks.

To generate expressions from a character vector, use parse(text=...):

lbls <- c("E^A","S^P","lambda","T","E^Q","E^Q","AT")    
x <- 1:length(lbls)
y <- runif(length(lbls))
# I'm just going to draw labels on the (x,y) points.
plot(x,y,'n')
text(x,y, labels=parse(text=lbls)) # see the parse(text=lbls) ?

enter image description here

like image 197
mathematical.coffee Avatar answered Sep 17 '22 20:09

mathematical.coffee