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"
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"
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)
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