iago
iago

Reputation: 3266

How to convert to numeric a sequence saved as a string?

How to convert to numeric a sequence saved as a string?

Let's have the string "3:7". I would like to get either c(3,4,5,6,7), or 3:7, anyway with R reading this data as numeric, not as string.

If I do as.numeric("3:7") I get a NA. Is there any simple way or function in R doing this?

A more complex example:

rec_pairs <- list(c("3:7", "1"), c("2,1", "3"), c("NA", "5"), c("6", "NA"))

I am interested in obtaining all the distinct elements in the first components of the vectors of the list, that is, 3,4,5,6,7,2,1,NA,6.

Upvotes: 1

Views: 764

Answers (2)

akrun
akrun

Reputation: 887821

We can use either eval(parse

eval(parse(text = "3:7"))

or split and convert use the seq

Reduce(`:`, scan(text="3:7", sep=":", what = numeric()))

Based on the new data

unlist(sapply(rec_pairs, function(x) lapply(strsplit(x[1], "[,:]"), 
       function(y) Reduce(`:`, as.list(as.numeric(y))))))
#[1]  3  4  5  6  7  2  1 NA  6

Upvotes: 2

ThomasIsCoding
ThomasIsCoding

Reputation: 102605

The method of eval and parse by @akrun would be the most efficient way. Here is another solution with base R:

v <- as.numeric(unlist(strsplit("3:7",":")))
s <- seq(v[1],v[2])

such that

> s
[1] 3 4 5 6 7

Upvotes: 0

Related Questions