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>")){
....
}
}
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>")) {
....
}
}
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>")) {
....
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With