emaoca
emaoca

Reputation: 109

Create a vector of numbers using character string

I spent a lot of time by searching a solution for that, in particular in this answer Use character string as function argument

Anyway I haven't found a solution.

I would use a string of character as it was my input in the console.

In particular, I can create vector v1 in this way

v1 <- c(1, 3, 5:10)

[v1] 1 3 5 6 7 8 9 10

I would like to find a way to do this by saving this code 1, 3, 5:10 as an object and than using it as it was my input

values <- ("1, 3, 5:10")

v1 <- c(read.as.input(values))

Any tips? Thanks

Upvotes: 0

Views: 744

Answers (3)

ThomasIsCoding
ThomasIsCoding

Reputation: 101064

You can try eval + str2lang

> eval(str2lang(sprintf("c(%s)", values)))
[1]  1  3  5  6  7  8  9 10

Upvotes: 1

vladli
vladli

Reputation: 1573

Is this what you want to achieve?

> a = "1, 3, 5:10"
> b = paste0("c(", a, ")") # paste characters inside c() to parse afterwards
> b
[1] "c(1, 3, 5:10)"
> eval(parse(text = b)) # parse it..
[1]  1  3  5  6  7  8  9 10

As a function:

> read.as.input <- function(input_text) {
 +     input_text = paste0("c(", input_text, ")")
 +     result = eval(parse(text = input_text))
 +     return(result)
 + }
> read.as.input("1,3,5:10")
[1]  1  3  5  6  7  8  9 10

Upvotes: 2

akrun
akrun

Reputation: 886938

We could create a grouping column based on the difference of adjacent elements, then use that group in tapply, to paste

toString(tapply(v1, cumsum(c(TRUE, diff(v1) != 1)), 
   FUN = function(x) if(length(x) > 1) paste(range(x), collapse=":") else x))
#[1] "1, 3, 5:10"

If it is the other way around

values <- c("1, 3, 5:10")
unlist(lapply(strsplit(values, ",\\s*")[[1]],
   function(x) eval(parse(text = x))), use.names = FALSE)
#[1]  1  3  5  6  7  8  9 10

Upvotes: 1

Related Questions