Y.P Y.P - 2 months ago 18
R Question

Loop compute inside cell R

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


We can use sapply

ds$B <- sapply(as.character(ds$B), function(x) eval(parse(text=x)))
#'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)