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

emaoca
  • 47
  • 3

3 Answers3

2

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
akrun
  • 874,273
  • 37
  • 540
  • 662
  • I think the asker wants a solution the other way around: to get `c(1,3,5:10)` from characters – vladli Apr 07 '21 at 17:51
  • @ClaudH I am not sure about the format he needs. In the post, it shows `values <- ("1, 3, 5:10")` as a single string – akrun Apr 07 '21 at 17:52
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
vladli
  • 1,454
  • 2
  • 16
  • 40
  • 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 – emaoca Apr 07 '21 at 18:08
2

You can try eval + str2lang

> eval(str2lang(sprintf("c(%s)", values)))
[1]  1  3  5  6  7  8  9 10
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81