1

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.

iago
  • 2,990
  • 4
  • 21
  • 27
  • Just want to point out that the edited example is pretty different from the original. Also, how are you defining distinct if you have 6 twice? – camille Dec 18 '19 at 15:53
  • Regarding to the "distinct" observation, you are right, it is a bad example (both 6 shoud be counted only once) – iago Dec 18 '19 at 15:55
  • But this is not a problem using later `unique` – iago Dec 18 '19 at 15:58
  • Right, but if the example you give doesn't match what you describe, then it's unclear that taking unique values would actually do what you want – camille Dec 18 '19 at 16:07

2 Answers2

2

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
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Thank you @akrun. I have `"3:7"` in a character vector of expressions result of applying `sapply`. Should I, following the answer https://stackoverflow.com/a/24975243/997979, add another `sapply` to eval the full vector of expressions or there is a shorter way? Thank you! – iago Dec 18 '19 at 15:33
  • @iago You can use `strsplit` into a `list` and then do the `Reduce` for each element. Please check the timings with benchmark – akrun Dec 18 '19 at 15:35
  • Following your indication, I try `Reduce(`:`, strsplit(sapply(rec_pairs, function(i) i[1]), split = ",", fixed = TRUE))` with the newer example I added to my question, but I get an error. – iago Dec 18 '19 at 15:42
  • @iago `strsplit` returns a string. Also, it can be directly applied on `rec_pairs` i.e. `lapply(strsplit(rec_pairs, ",", fixed = TRUE), function(x) Reduce(`:`, as.list(as.numeric(x))))` – akrun Dec 18 '19 at 15:44
  • It gives me an error: `rec_pairs` is a list and `strsplit` only applies to vectors. Further I do not want all the elements in `rec_pairs` – iago Dec 18 '19 at 15:51
  • I added to my question – iago Dec 18 '19 at 15:53
0

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
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81