[R] Data consistency checks in functions

Mike Meredith mmeredith at wcs.org
Sat Jun 23 11:23:26 CEST 2007



Take a look at Help > Manuals (in PDF) > An Introduction to R, section 10.3.

R will recognise the 2nd argument as 'values' iff you define your function
as:

myfun <- function(theta, values, X)

You can use

if(missing(values)) {
   values <- some.expression(X)
}

to deal with cases where the user only supplies 1 argument.

Where does 'X' come from? If it's a predefined default (maybe something like
'cbind(1:4, 1, 0)' ), better to define it within your function. If it's some
object 'X' lurking in the user environment, it could be changed by the user,
so you don't know what it might be. A way around this is to require the user
to provide either a vector or a matrix as the second argument, then sort
them out with:

if(is.matrix(values)) {
   values <- same.expression.as.before(values)
}

HTH,  Mike.




Anup Nandialath wrote:
> 
> Dear friends,
> 
> I'm writing a function with three arguments
> 
> myfun <- function(theta, X, values)
> 
> {
> ....
> ....
> }
> 
> in this function, I'm trying to write consistency checks. In order to
> compute the statistic of interest I only need theta and values. The idea
> of having X in there is that, if values is not provided by the user, then
> values is computed from X.
> 
> my problem is I'm trying to write consistency checks. For instance if i
> say
> 
> output <- myfun(beta, val1), how do I ensure that R reads this as passing
> arguments to "theta" and "values". In other words is it possible to bypass
> X completely if values is provided. Also how is it possible for R to
> recognize the second argument as being values and not X. This is important
> because X is a matrix and values is a vector. Therefore any checks using
> the dimensions of either one will land in trouble if it does not correctly
> capture that. 
> 
> Thanks in advance
> Sincerely
> 
> Anup
> 
>        
> ---------------------------------
> 
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
> 
> 

-- 
View this message in context: http://www.nabble.com/Data-consistency-checks-in-functions-tf3962728.html#a11264566
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list