Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having R ignore an argument in a function

Tags:

function

r

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}
like image 673
rnorouzian Avatar asked Sep 19 '25 17:09

rnorouzian


1 Answers

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 }
like image 129
G. Grothendieck Avatar answered Sep 21 '25 08:09

G. Grothendieck