Sriharsha
Sriharsha

Reputation: 160

read input from keyboard in R

I know this is very basic question as I am new to R I have this question.

How to allow users to enter numbers from the keyboard. Provide users to enter how many numbers they want to enter from key board and according to that provide facility to enter numbers.

eg:

How many numbers you want to enter?  
> 10  
Enter numbers:  
> 5 10 15 20 25 30 35 40 45 50

Upvotes: 3

Views: 10723

Answers (3)

Waldir Leoncio
Waldir Leoncio

Reputation: 11341

As others have already anwered, readline is the function that answers your question. About your example, here's an attempt to reproduce the requested behavior.

N <- as.numeric(readline("How many number do you want to enter? "))
x <- vector()  # making sure x is empty

for (n in seq_len(N)) {
    new_x <- readline(paste0("Enter number ", n, " of ", N, ": "))
    x <- append(x, as.numeric(new_x))
}

cat("Here are the entered numbers:\n")
print(x)

Upvotes: 0

Sriharsha
Sriharsha

Reputation: 160

I have created a function that will asks the users How many numbers they want to enter and based on that count it provides facility to enter the integers

readnumber <- function()
{ 
    n <- readline(prompt="How many numbers do you want to enter: ")
    n <- as.integer(n)
    if (is.na(n)){
        n <- readnumber()
    }
    Numbers<-c()
    for (i in 1:n){
        num <- readline(prompt="Enter an integer: ")
        Numbers[i]<-as.numeric(num)
    }
    return(Numbers)    
}
print(readnumber()) 

Upvotes: 0

InspectorSands
InspectorSands

Reputation: 2939

   while(T) {
    num <- readline("How many number do you want to enter? > ")
    num <- as.numeric(num)
    if (!is.na(num)) {
      num2 <- readline(paste0("Enter ",num, " numbers > "))
      print(num2)
      break
    }
  }

Upvotes: 2

Related Questions