Error with interactive menu function when running block code

Asked

Viewed 78 times

2

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

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

But it is part of a program that uses this requested number in functions further ahead.

When I run the line of code separately it works well, when running in block it reads each line of code as answer to that question and therefore gives error.

I’ve tried to:

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

and

file("stdin")

But nothing works.

1 answer

3

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

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

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

To source from the command line, first you must 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 turn source("teste.R"). You will see that the prompt will appear correctly and variable y will have the correct value of x+1, what does not occur when rotating in block.

  • Thank you for your reply, but it is still a mistake. I wrote a file with the menu function, and then in the complete file where I have the rest of the source code("filename.R") but still R continues to take each line of code as an answer to the question of the menu function

  • @Rita This minimal example I put works on your computer?

  • Yes, this example works @Carlos Cinelli

  • And when I run the "source" function alone in my code it works fine too. The problem is that this function is part of a complete program and when I use "Run all", then the code takes each line of code as a response and gives error

  • @Rita, I don’t understand, but are you running "run all" or "source"? Run all won’t work anyway. Try creating a minimal example that reproduces the problem and put it here.

  • Thank you @Carlos Cinelli. I already managed to solve the problem, as the choice I want was only between three numbers, to use the menu function and run the program with "run all", just add in the menu function "Graphics=TRUE"

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.