rnorouzian
rnorouzian

Reputation: 7517

Having R ignore an argument in a function

I'm writing a function for two types of t-tests (paired, independent samples). The function takes the arguments (n1, n2, ttype). n1 and n2 are sample sizes. ttype determines whether the t-test is paired (=1) or independent (=2).

How can I make R understand when n2 is missing or is.na(n2)(i.e., n2= no number in front of it), take the input as representing a ttype = 1 and even if there is an n2 "ignore" the n2 ?

I'm using the below code, but keep getting the error message that:

"argument "n2" is missing, with no default"

if(missing(n2) | is.na(n2)){n2 <- NA; ttype <- 1}

Upvotes: 4

Views: 1698

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 269556

Your code should work if you use || instead of |. With || it short circuits, i.e. it works from left to right and only evaluates the right hand side if the left hand side is FALSE; however, with | both sides are evaluated first (which results in an error if n2 is missing) and then it combines them.

if (missing(n2) || is.na(n2)) { n2 <- NA; ttype <- 1 }

Upvotes: 3

Related Questions