Danilo Katzaroff
Danilo Katzaroff

Reputation: 3

In R, how to read multiple integers from user prompt?

I need to create a vector with multiple inputs (integers) from user.

The intent is to create a list and verify if it has a mode and where is its median.

I am using this code:

ReadVector <- function()
{ 
  x <- 0
  while(x<16) {
  n <- readline(prompt="Input one integer: ")
  return(as.integer(n))
  VectorUser <- c(n)
  x <- x+1
  } 
  print(VectorUser)
  }

ReadVector()

And I can only get one integer, I dont know if my mistake is in the while loop or(and) in the concatenate command after it. Can you help me?

Upvotes: 0

Views: 2209

Answers (2)

Onyambu
Onyambu

Reputation: 79238

ff=function(){
  d=c()
  while (TRUE){
    int = readline('ENTER to quit > ')
    if(nchar(int)==0) {
      if(length(d)>0)cat("The numbers you entered are:",d)
      else(cat("You did not enter any number!!"));break}
    else{
      value=suppressWarnings(as.integer(int))
      if(!is.na(value)){cat(value);d=c(d,value)} else cat(ran[sample(6,1)])
    }}
ff()

Upvotes: 0

elcortegano
elcortegano

Reputation: 2684

Does this work for you?

ReadVector <- function()
{ 
  x <- 0
  myvector = vector()
  while(x<16) {
    n <- readline(prompt="Input one integer: ")
    myvector = c(myvector,n)
    x <- x+1
  } 
  return (as.integer(myvector))
}

You need yo save your values in a vector, and keep it (without returning inside the loop), until you completed it.

Hope it helps

Upvotes: 2

Related Questions