[R] Using a data frame in a function call

Charles C. Berry cberry at tajo.ucsd.edu
Tue Oct 23 20:13:42 CEST 2007


On Tue, 23 Oct 2007, Peter Tait wrote:

> Hi,
>
> I am writing a basic function to extract the z scores for some linear
> regression coefficients:
>
> zscore<-function( y, x) {
>  lm<-lm( y ~ x )
>  z <- coef(lm)/sqrt(diag(vcov(lm)))
>  return(z)
> }
>
> I would like to pass a dataframe to the function as a argument so the
> function call changes from
>
> zscore(df$y1,df$x1)
>
> to
>
> zscore(y1,x1,data=df)
>
> but I am not sure how to reference the data frame inside the function.
>
> Are there any good free references on how to program functions in R (besides
> the official manuals)


Yes. You are wandering into territory that may get a bit tricky, but the 
source code is excellent in this regard.

 	page(lm,'print')

will print a copy of the code for lm(), which handles data.frames and has 
been carefully worked to do it well.

Looking at that code should be very instructive.

In addition, stepping thru the code is very helpful. Something like

 	example( lm )
 	debug( lm )
 	lm(weight ~ group)
 	<< hit ENTER a few times, then ...>>
 	cl
 	cl[[1]]
 	cl[[2]]

and so on - inspecting the objects lm() creates as it is creating them, 
will let you see just how lm() puts together all its args to form a 
model.matrix, carry out the regression, and assemble its 'value'

Be sure to check out 'mf' before and after each step in which it is 
modified.

Chuck


>
> Thanks for your help.
> Cheers
> Peter
>
> ______________________________________________
> R-help at r-project.org 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.
>

Charles C. Berry                            (858) 534-2098
                                             Dept of Family/Preventive Medicine
E mailto:cberry at tajo.ucsd.edu	            UC San Diego
http://famprevmed.ucsd.edu/faculty/cberry/  La Jolla, San Diego 92093-0901



More information about the R-help mailing list