Convert in R character formulas to numeric

Viewed 164

How can I convert y vector into a numeric vector.

y <- c("1+2", "0101", "5*5")

when I use

as.numeric(Y)

OUTPUT

Na 101 NA

2 Answers

The following code

sapply(y, function(txt) eval(parse(text=txt)))

should to the work.

The problem is quite deep and you need to know about metaprogramming. The problem with as.numeric is, that it only converts a string to a numeric, if the string only consists of numbers and one dot. Everything else is converted to NA. In your case, "1+2" contains a plus, hence NA. Or "5*5" contains a multiplication, hence NA. To say R that it should "perform the operation given by a string", you need eval and parse.

An option with map

library(purrr)
map_dbl(y, ~ eval(rlang::parse_expr(.x)))
#[1]   3 101  25
Related