2

How can I take this

d <- "3:10"

and magically turn it into this

[1]  3  4  5  6  7  8  9 10

I've seen this done before, and searched SO extensively, but was unable to recall anything.

Here's what I've tried.

> eval(d)
# [1] "3:10"
> eval(noquote(d))
# [1] 3:10
> noquote(eval(d))
# [1] 3:10
> evalq(d)
# [1] "3:10"
> substitute(d)
# d
Rich Scriven
  • 97,041
  • 11
  • 181
  • 245

1 Answers1

4

I think you are looking for the dreaded eval(parse(...)) construct.

Try:

d <- "3:10"
eval(parse(text = d))
# [1]  3  4  5  6  7  8  9 10

An interesting approach to this could be:

Reduce(":", as.numeric(strsplit(d, ":", TRUE)[[1]]))
# [1]  3  4  5  6  7  8  9 10

And, whaddyaknow! I wouldnathunkit, but it's faster than eval(parse(...)) (but your approach in the comment is faster yet).

fun1 <- function() Reduce(":", as.numeric(strsplit(d, ":", TRUE)[[1]]))
fun2 <- function() eval(parse(text = d))
fun3 <- function() {
  s <- as.numeric(strsplit(d, ":", fixed = TRUE)[[1]])
  s[1]:s[2]
}

library(microbenchmark)
microbenchmark(fun1(), fun2(), fun3())
# Unit: microseconds
#    expr     min       lq   median       uq     max neval
#  fun1()  24.375  26.0865  32.2865  55.8070 113.751   100
#  fun2() 108.192 112.4680 121.4490 204.8375 453.720   100
#  fun3()   8.553  10.6920  12.8300  20.9550  40.198   100
A5C1D2H2I1M1N2O1R2T1
  • 190,393
  • 28
  • 405
  • 485