Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R function; if input is not given, ask for it

Tags:

r

I'm trying to write a function in R that takes two inputs as strings. If neither input is set, it asks for the inputs and then continues the function.

Input < - function(j,k){
   if ((j==j)&&(k==k)){
      j <- readline(prompt="Enter Input 1: ")
      k <- readline(prompt="Enter Input 2: ")
      Input(j,k)
   }else if ((j=="<string here>")&&(k=="<string here>")){
      ....
   }
}
like image 510
LemonSkin Avatar asked May 11 '15 01:05

LemonSkin


2 Answers

I think the better way to structure your approach would be this, using optional arguments and testing to see if they are non-null before proceeding, though admittedly your posted question is very vague:

Input < - function(j=NA, k=NA) {
  if (is.na(j) | is.na(k)){
    j <- readline(prompt="Enter Input 1: ")
    k <- readline(prompt="Enter Input 2: ")
    Input(j, k)
  } else if ((j == "<string here>") & (k == "<string here>")) {
    ....
  }
}
like image 109
Forrest R. Stevens Avatar answered Sep 28 '22 19:09

Forrest R. Stevens


Although I personally prefer the is.NA or is.NULL (as in @Forrest 's answer), this is an alternative with missing that might look simpler for someone starting now with R.

Input <- function(j, k) {
  if (missing(j) | missing(k)){
    j <- readline(prompt="Enter Input 1: ")
    k <- readline(prompt="Enter Input 2: ")
    Input(j, k)
  } else if ((j == "<string here>") & (k == "<string here>")) {
    ....
  }
}
like image 33
LyzandeR Avatar answered Sep 28 '22 18:09

LyzandeR