Error with interactive menu function when block code runs

2

I have a line of code that asks the user for a number like this:

menu(c('1','2','3'), title='Escolha um número:')

But that is part of a program that uses this number requested in functions later.

When I run the line of code separately it works fine, while running block reads each line of code in response to that question and therefore gives error.

I've tried:

scan("stdin", character(), n=1)

and

file("stdin")

But nothing works.

    
asked by anonymous 16.05.2017 / 21:10

1 answer

3

Running the block code is the same as interactively commands for the console. That way, when you run block code, R will find that the line just after menu() is the answer to menu() , since R is only receiving each command iteratively.

However, if you give source() to your code you will have the behavior you want.

If you are using RStudio , an easy way to give source is to click on the "source" button of the script or use the shortcut key crtl (or cmd to mac) + shift + enter .

To give source from the command line, you must first save your script and then call source("nomedoscript.R") .

For a minimal example, save the code below in teste.R :

rm( list = ls())
x <- menu(c('1','2','3'), title='Escolha um número:')
y <- x + 1

And then run source("teste.R") . You will see that the prompt will appear correctly and variable y will have the correct value of x+1 , which does not occur by running in block.

    
17.05.2017 / 03:28