0

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

3 Answers 3

2

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

1 Comment

yeah, it was exactly this. My problem was that I wasn't able to force readLine syntax like "1,3,5:10" into input to create a vector. Your answer has answered my question! many thanks
1

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

2 Comments

I think the asker wants a solution the other way around: to get c(1,3,5:10) from characters
@ClaudH I am not sure about the format he needs. In the post, it shows values <- ("1, 3, 5:10") as a single string
1

You can try eval + str2lang

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

1 Comment

This should be the best solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.