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
0

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

11 Comments

Aha! Curious, why is it "dreaded"? Many people on SO say that, about eval especially. Is it better to go with s <- as.numeric(strsplit(d, ":")[[1]]); s[1]:s[2] ?
@RichardScriven, fortune(106)? I'll dig up a couple of links. I've never had any problems with it myself though.
@RichardScriven, actually, this search brings up the most relevant reasons for the eval(parse(...)) construct. Regarding your subquestion, how did the data get in this form?
I'm parsing the text from this link to create the header vector for the data it goes with. So I wanted to create these sequences to go along with the result from my other question
@DavidArenburg, try d <- "12:18" with your approach.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.