R-function; if the input is not specified, ask him

I am trying to write a function in R that takes two inputs as strings. If no input is set, it requests inputs, and then continues to work.

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>")){ .... } } 
+7
r
source share
3 answers

I think the best way to structure your approach would be to use optional arguments and testing to see if they are nonzero before continuing, although 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>")) { .... } } 
+3
source share

Although I personally prefer is.NA or is.NULL (as in @Forrest's answer), this is an alternative with missing , which might look easier for someone starting 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>")) { .... } } 
+3
source share

I think the easiest way is to put readline code as an argument. The force commands force this code to be evaluated at this point in the function. I don't think they are necessary, but depending on what else the function does, you may want it to ask j and k first, and not later; otherwise the code will be evaluated when it first needs to know that j and k .

 Input <- function(j = readline(prompt="Enter Input 1: "), k = readline(prompt="Enter Input 2: ")) { force(j) force(k) if ((j=="<string here>") && (k=="<string here>")) { .... } } 
+3
source share

All Articles