Search code examples
rvectorconsole-input

How can I store user-input as a vector (for a certain range e.g. c(-10:1)?


I'm new to R. And I want to make a program that asks for console input and then does some things, including making a graph. And now I want the user to specify the x-values for the graph. And then I want to do that with a range, for example c(-10:10).

When I use the readline() function I only get a string value.

myvector <- readline("Give the range for x-values") ### results in string value
c(-10:10)
myvector

I get "c(-10:10)", but that is not what I want. How can I get a vector (c(-10:10) from user input? Or how can I convert this string to a vector?

Thanks in advance!


Solution

  • You are capturing a character vector, so you need to parse it and evaluate it like so. Also note that the argument to xlim is a range.

    res <-eval(parse(text=myvector))
    plot(-20:20,xlim=range(res))
    

    enter image description here