1

I have a vector of numbers and characters that are treated as characters, for example:

mix <- c("50", ">10^4", "<10", "325") 

I understand how to strip off the > and < and apply as.numeric(). However, this results in a NA value for "10^4".

I've tried to use eval("10^4") however this doesn't work and simply returns the character.

Currently, my function is:

f_convert2numeric <- function(vec){
  nvec = eval(as.numeric(gsub(">","",gsub("<","",vec))))
  return(nvec)
}

Is there any way to add in this ability to convert characters using ^ to numeric? Preferably in base R but happy with alternatives.

Jaap
  • 81,064
  • 34
  • 182
  • 193

1 Answers1

2

Using:

sapply(gsub("[<>]", "", mix), function(x) eval(parse(text = x)), USE.NAMES = FALSE)

gives:

[1]    50 10000    10   325

If you omit USE.NAMES = FALSE, you will get a named vector:

   50  10^4    10   325 
   50 10000    10   325

It might be worthwhile to consider vapply over sapply (see here for an explanation why this is safer):

vapply(gsub("[<>]", "", mix), function(x) eval(parse(text = x)),
       FUN.VALUE = 1, USE.NAMES = FALSE)
Jaap
  • 81,064
  • 34
  • 182
  • 193
  • 1
    Thank you very much, `parse()` was a very vital component I was missing! And appreciate the tidying of my clunky code! – Ben Francis May 08 '19 at 08:26