Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in R Programming by (3.9k points)

I'm curious to know if R can use its eval() function to perform calculations provided by e.g. a string.

This is a common case:

eval("6+6")

However, instead of 10 I get:

[1] "6+6"

Any solution?

1 Answer

0 votes
by (46k points)

eval() function is used to evaluate an expression, not a string, as in your case "6+6" is a string. So to convert a string into the expression you need to use parse() with text=<string>

> eval(parse(text="6+6"))

[1] 12

> class("6+6")

[1] "character"

> class(parse(text="6+6"))

[1] "expression"

> class(eval(parse(text="6+6")))

[1] "numeric"

If you face an error in eval(), use this syntax after executing the above code:

main <- function ()

{

 returnStringValue <- "ignore"

 return (returnStringValue)

}

Related questions

+1 vote
1 answer
asked May 29, 2019 in R Programming by Ritik (3.5k points)
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...