[R] moving onto returning a data.frame?

Thomas Lumley tlumley at u.washington.edu
Wed May 21 16:15:12 CEST 2003


On Tue, 20 May 2003, Jeff D. Hamann wrote:
> Does anyone have a good example (from some of the packages?) for returning a
> data.frame. I'm trying to start my function so that it takes a data.frame as
> an argument and returns a data.frame (post-hocus-pocus).

read.dta in the foreign package springs to mind since I updated it
yesterday.  There are probably many others.

> Here's my function so far...
>
> SEXP testfunction3(
>    SEXP m_in )
> {
>
>    int *mdims, n, p, i;
>    double *mm;
>
>    SEXP m_out;
>    SEXP nms;
>
>    if( !isMatrix( m_in ) )
>    {
>       error("m_in must be a matrix");
>    }
>
>
>
>    mdims = INTEGER( GET_DIM( m_in ) );
>    n = mdims[0];
>    p = mdims[1];
>    PROTECT( m_out = NEW_NUMERIC( p ) );

You are creating a vector of p reals here, not a data frame. If you know
the input and output have the same sizes and types it might be easiest to
use
    m_out = duplicate(m_in)
though this is not maximally efficient.

>    PROTECT( m_in = AS_NUMERIC( m_in ) );
>    PROTECT( nms = GET_COLNAMES( GET_DIMNAMES( m_in ) ) );
>
>     /* here you'll disect the incoming data.frame into the vectors you'll
> pass into your simulation code */
>     /* get the vectors based on the column names to make sure the sequence
> isn't important */
>
>     /* crunch, crunch, crunch */
>
>     /* assign the results into the outgoing data.frame which will have the
> same dimensions as the incoming frame */
>
>
>     if( !isNull( nms ) )
>    {
>       namesgets( m_out, nms );
>    }
>
>    UNPROTECT( 3 );
>
>    return m_out;
> }
>

	-thomas

Thomas Lumley			Asst. Professor, Biostatistics
tlumley at u.washington.edu	University of Washington, Seattle




More information about the R-help mailing list