[R] accessing factor levels from C

Prof Brian D Ripley
2002-03-02T16:05:24Z

On Sat, 2 Mar 2002, Ott Toomet wrote:

> Hi,
>
> I am trying to get information about factors from a C-program.  As I see,
> the factors are basically integers with attribute ,,levels''.  But
> unfortunately I am not been able to read the levels information.  I am
> using:
>
> SEXP variable, levels;
>
> ...
>
>       variable = VECTOR_ELT( data_frame, j);
>       switch( TYPEOF( variable)) {
>       case INTSXP:
> 	if( isFactor( VECTOR_ELT( data_frame, j))) {
> 	  fvalue = INTEGER( variable)[i];
> 	  levels = STR_PTR( GET_LEVELS( variable));
> 	....
>
>
> but the variable levels is not an array of strings as I expected.  I am
> probably doing something in the wrong way but how would it be correct?

GET_LEVELS gives you an R character vector.  That is not an array of
strings.  (What is STR_PTR, by the way?  It's not in Rdefines.h, and
strings are not handled in the same way as, say, numeric vectors.  And
beware of some of the macros in Rdefines.h, which predate changes in R
1.2.0.)

Use something like

   lev = getAttrib(variable, R_LevelsSymbol);
   thislevel = CHAR(STRING_ELT(lev, i))

for the ith level.  There are some examples in seq.c. The first is what
GET_LEVELS expands to.

--
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272860 (secr)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at
stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._