Search code examples
rcharacternumeric

Convert character colony-forming units to numeric scientific notation in R


Say I have a following character vector with data on colony-forming units for a particular bacteria species

head(data$bacteria)
[1] "3*10^5" "2*10^6" "10^4"   "7*10^7" "3*10^6" "2*10^7"

I want the chr vector with theese arythmetics to be a vector with numeric result of this arythmetic expression in scientic notation so that I can run some statistical tests I tried using as.numeric but it coerced the data to NAs

as.numeric(data$bacteria)
NAs introduced by coercion [1] NA NA NA NA NA NA...

How do I convert a character vector with math expression to a numeric result of theese expressions in scientific notation without loosing information?


Solution

  • You can use :

    sapply(data$bacteria, function(x) eval(parse(text = x)), USE.NAMES = FALSE)
    

    Eg -

    x1 <- c("3*10^5" ,"2*10^6", "10^4",   "7*10^7","3*10^6", "2*10^7")
    sapply(x1, function(x) eval(parse(text = x)), USE.NAMES = FALSE)
    #[1] 3e+05 2e+06 1e+04 7e+07 3e+06 2e+07