Madhu Sareen
Madhu Sareen

Reputation: 549

In R, how to read an integer from user prompt?

I am trying to read an integer from user prompt. But it is reading as character. How to read it as integer?

myfunt <- function(){
 cat("Enter an integer or whole number : \n")
 enter <- readline(prompt = "")
 cat("You sumitted : \n"); str(enter)
}

Running this function produces: myfunt()

Enter an integer or whole number: 
17
You sumitted : 
chr "17"

Any solution?

Upvotes: 1

Views: 7351

Answers (2)

Vin
Vin

Reputation: 151

Generally 'readline' function takes data into character value.

In order to convert these character into numeric values, you can make use of below code into your function,

If you have only one number to be converted into a numeric value,

num <- readline("Enter a number : ")
num <- as.numeric(unlist(num))

If you have multiple numbers to be converted into a numeric value,

num <- readline("Enter the sequence of numbers separated by comma : ")
num <- strsplit(num,',')
num <- as.numeric(unlist(num))

Upvotes: 0

Manoj Kumar
Manoj Kumar

Reputation: 5647

Ahh ! simple... just use as.integer()

myfunt <- function(){
 cat("Enter an integer or whole number : \n")
 enter <- as.integer(readline(prompt = ""))
 cat("You sumitted : \n"); str(enter)
}

and running your function.. myfunt()

Enter an integer or whole number: 
17
You sumitted : 
int 17

Upvotes: 2

Related Questions