Skip to content

accessing factor levels from C

2 messages · Ott Toomet, Brian Ripley

#
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?

Thanks in advance,

Ott Toomet

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
#
On Sat, 2 Mar 2002, Ott Toomet wrote:

            
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.