Home > Software engineering >  convert characters to numeric range in r?
convert characters to numeric range in r?

Time:05-29

I have a simple problem. I have set of vector (characters). I want to convert them into numeric along with colon operator.

a <- c("10:20", "25:30")
print (a)

[1] "10:20" "25:30"

as.numeric(a)

[1] NA NA

Warning message:

NAs introduced by coercion

This is the error i'm getting.

The expected output is

10:20
20:30

I tired this but did not work the way i expected

strapply(a, "(\\d ):(\\d )")

CodePudding user response:

It's difficult to know what you mean by the expected output. Taking you literally, you want the strings converted to calls:

 lapply(a, function(x) as.call(parse(text = x))[[1]])
#> [[1]]
#> 10:20
#>
#> [[2]]
#> 25:30

My guess is that this is not what you meant, and instead you want the strings to be evaluated, in which case you could do:

lapply(a, function(x) eval(parse(text = x)))
#> [[1]]
#> [1] 10 11 12 13 14 15 16 17 18 19 20
#>
#> [[2]]
#> [1] 25 26 27 28 29 30

However, this is fairly unsafe, since it would be easy to write a malicious string that caused problems on your computer if the data was not always checked for safety beforehand.

A safer way to do this would be

lapply(strsplit(a, ":"), function(x) x[1]:x[2])
#> [[1]]
#>  [1] 10 11 12 13 14 15 16 17 18 19 20
#> 
#> [[2]]
#> [1] 25 26 27 28 29 30

which will throw an error if the string isn't in the correct format rather than running arbitrary code on your computer.

  • Related