How to enter an integer interactively in R
Dear all, I would want to enter an integer interactively into R and then capture it and use it in my code. I was trying it with the scan() function but it gave me errors! This is what I have done:
#This is my question
print("enter a positive integer")
n <- scan()
while(is.numeric(n) == F){
print("enter a positive integer")
n <- scan()
}
Also, after the execution of the first开发者_如何学Python line, I want the program to pause for me to enter n before it checks the while loop
#This part is not part of my question; after capturing n I would want to use it in a code like this.
c <- ncol(d)
r <- nrow(d)
for(i in 1:c) {
d[n,i] <- 0
}
many thanks to all who could be of help. Isaac Owusu
Try:
n <- scan (what=integer(), nmax=1, quiet=T)
This won't work while you're just pasting it into the terminal. You actually have to source it from a file for scan() to work properly. That's because when you paste it in then it immediately executes scan, then executes the carriage return after scan... etc. So, save this in a file, 'myfile.R', and type
source('myfile.R')
Once you get that far then you probably need to edit how you're using scan(). It fails with error if the wrong type is entered so you need a try() statement. The way you're doing it integers that are entered will always be real. Also, as has been posted in another answer, set nmax to 1. The following will do what you want... although still a little oddly (as you'll see).
n <- NULL
while(is.numeric(n)==F){
print("enter a positive integer")
try(n <- scan (what=integer(), nmax=1), silent = TRUE)
}
If on Windows you could use dialog boxes:
n <- winDialogString("enter a positive integer","")
It will always return character so you have to do necessary conversions and test.
E.g.:
isPositiveInteger<-FALSE
while(!isPositiveInteger) {
n <- winDialogString("enter a positive integer","")
isPositiveInteger <- grepl("^[1-9][0-9]*$", n)
}
n <- as.integer(n)
精彩评论