Problem reading readline keyboard input on R

Asked

Viewed 137 times

-5

Hello, I’m trying to do this program there in rstudio, but when I select everything to run, it gives this error. If I put it to run the first line and then the rest, then it runs the program straight. Maybe it’s something stupid that I’m not aware of. And neither this and other programs you do in rstudio.

To follow my code:

 id = as.integer(readline(prompt = "Escreva sua idade: "))
  
 if(id >= 0 && id < 18){
   print("você é uma criança")
 }
 else if(id >= 18 && id <= 50){
   print("você é adulto")
 }
 else print("você é um adulto experiente")

inserir a descrição da imagem aqui

  • Without a reproducible example It’s hard to help, @Lenesson.

  • You can see on the top right of Rstudio that the id is valued NA (NA_integer_). This causes the error in question. Here’s how you’re setting this variable

  • It seems to have relation to all two things right, without giving type what a user would type in age.

3 answers

1

From what I understand of your code, when the program asked the question Escreva sua idade:

You did not enter a valid integer (for example, enter a string a or just type <enter>), but this value is needed to execute if. Since the read value is stored in the variable id.

The error occurs because the value id is void.

One way to treat this error is to check if the read value is a valid integer before executing the logic present in if.

  • When I run the whole program (selecting everything and pressing in run) it prints all my code, from this error before it even appears for me to type

1

The problem is in the first statement. The function readline shall be executed on a separate line, with or without as.integer. Otherwise, when you switch to the next instruction you are sending a <Enter> (be it <CR> be it <CR><LF>) automatically.

Run the first line of code by entering a number.

Then yes, you can select and execute all the rest of the code.

0

If you want all the code to be executed at once, without the id value being assigned to the part, you can try a functional approach by transferring the method into a function. Thus:

verificadorIdade <- function(){
  id <- as.integer(readline(prompt = 'Escreva sua idade: '))
  
  if(id >= 0 && id < 18){
    print('você é uma criança')
  }
  else if(id >= 18 && id <= 50){
    print('você é adulto')
  }
  else print('você é um adulto experiente')
}

The only difference here is that I created a function, called verificadorIdade and put your code as method. So when you run the command verificadorIdade() the code will work perfectly. Remember to perform the function before, so that the R saves it in memory

Browser other questions tagged

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