1

I have this data.frame for example:

ds = data.frame(A= c("a","b","c","d") ,B= as.factor( c("4*10^4","2*10^3", "5000", "8*10^7")) )

I want to convert the column B to numeric and compute values inside it.

This code work for 1 cell:

eval(parse(text = "4*10^4"))

But when I try to loop over all my column with this line:

ds$B = for (i in ds$B) {eval(parse(text=i))}

It delete my column

Y.P
  • 355
  • 2
  • 12
  • 3
    Possible duplicate of [In R, evaluate expressions within vector of strings](http://stackoverflow.com/questions/24975229/in-r-evaluate-expressions-within-vector-of-strings) – konvas Nov 15 '16 at 15:17

2 Answers2

3

We can use sapply

ds$B <- sapply(as.character(ds$B), function(x) eval(parse(text=x)))
str(ds)
#'data.frame':   4 obs. of  2 variables:
#$ A: Factor w/ 4 levels "a","b","c","d": 1 2 3 4
#$ B: num  4e+04 2e+03 5e+03 8e+07

Or if we are using the for loop, loop through the sequence of 'B' after converting to character class.

ds$B <- as.character(ds$B)
for(i in seq_along(ds$B)) ds$B[i] <- eval(parse(text=ds$B[i]))
ds$B <- as.numeric(ds$B)
akrun
  • 874,273
  • 37
  • 540
  • 662
1

Try this

eval(parse(text = paste0("c(", paste(ds$B, collapse = ","), ")")))
# [1] 4e+04 2e+03 5e+03 8e+07

What it does is convert your vector of strings ds$B to the string "c(40000, 2000, 5000, 8e+07)" and then parses it.

konvas
  • 14,126
  • 2
  • 40
  • 46