[R] Rpart and case weights: working with functions

Xavier Robin Xavier.Robin at medecine.unige.ch
Tue Jun 3 11:33:06 CEST 2008


I can't get rpart accept case weights defined inside a function.
It keeps using the copy defined in the "global" environment (if they 
exists) instead of the function-defined ones.

Here is what I do:

test.function <- function (formula, data) {
   weights <- rep(.1, 100)
   rpart(formula, data, weights)
}

test.function(x~y, data)

And I get an error:
> Error in model.frame(formula, rownames, variables, varnames, extras, extranames,  : 
>         invalid type (closure) for variable '(weights)'


If I define weights in the global environment, it uses this instead of 
the function-defined one (which can be verified by 
.Last.value$frame$wt[1]: it should equal sum(weights) and actually 
equals the sum of global weights, not the function one).

I tried to pass a named argument (weights=weights), using other names 
(w, foo, ...), or both, but still it doesn't work. I found nothing in 
rpart doc about that behaviour...
It was tested on R 2.7.0 (Windows XP) and R 2.5.1 (Linux kernel 2.6.9).

For the moment, the only workaround I found is to use/modify the global 
weights using <<- (not very satisfying).


What did I wrong? And what should I do to get it work (i.e. using the 
copy of weights defined inside the function)?

Thanks in advance for your help.

Xavier Robin

-- 
Xavier Robin

Biomedical Proteomics Research Group (BPRG)
Department of Structural Biology and Bioinformatics (DBSB)
Geneva University Medical Center (CMU)
1, rue Michel Servet - CH-1211 Genève 4 - Switzerland
Tel: (+41 22) 379 53 21



More information about the R-help mailing list