1

Trying to coerce this vector as numeric:

vec <- c("10^2", "10^3", "10^6", "", "10^9")

vec <- as.numeric(vec)

[1] NA NA NA NA NA

Warning message:
NAs introduced by coercion

Output desired:

[1] "100" "1000" "1e+06" "" "1e+09"

2 Answers2

1

Here, we can use eval(parse as it is a expression

lst1 <- lapply(vec, function(x) eval(parse(text = x)))
lst[sapply(lst1, is.null)] <- NA
unlist(lst1)
#[1] 1e+02 1e+03 1e+06    NA 1e+09

Or in a compact way, replace the blank ("") with NA and then do the eval(parse

sapply(replace(vec, vec == "", NA), function(x) eval(parse(text = x)))

Or another option is to read with read.table using sep as ^ and then use

with(read.table(text = paste(vec, collapse="\n"), sep="^", header = FALSE), V1^V2)

Or as @d.b suggested

read.table(text = paste(gsub("0\\^", "e", replace(vec, vec == "", NA)),
     collapse="\n"), header = FALSE)
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 1
    You might as well do `eval(parse(text = paste0("c(", paste(replace(vec, vec == "", NA), collapse = ","), ")")))` – d.b Sep 17 '19 at 17:56
  • 1
    Also, `read.csv(text = paste(gsub("0\\^", "e", vec), collapse = ","), header = FALSE)` – d.b Sep 17 '19 at 17:59
1

split the strings at ^ and then coerce each part individually. We have to escape using \\ because ^ is a special regex character.

sapply(strsplit(vec, "\\^"), function(x){
    as.numeric(x[1])^as.numeric(x[2])
})
#[1] 1e+02 1e+03 1e+06    NA 1e+09
d.b
  • 32,245
  • 6
  • 36
  • 77