[Rd] question regarding lang2 command in C

Romain François romain at r-enthusiasts.com
Thu Apr 3 08:25:26 CEST 2014


Hi, 

This is easy if the gender and age are already vectors of some sort of the same size. 

SEXP df = PROTECT(allocVector(VECSXP, 2)); 
SET_VECTOR_ELT(df,0,gender) ;
SET_VECTOR_ELT(df,1,age) ;
SEXP names = PROTECT(allocVector(STRSXP,2));
SET_STRING_ELT(names,0,mkChar("age"))
SET_STRING_ELT(names,0,mkChar("gender"))
setAttrib(df, R_NamesSymbol, names );
setAttrib(df, R_ClassSymbol, mkString("data.frame"));
SEXP rn = PROTECT(allocVector(INTSXP,2)); 
INTEGER(rn)[0] = NA_INTEGER ;
INTEGER(rn)[1] = -length(gender);
setAttrib(df, R_RowNamesSymbol, rn) ;
UNPROTECT(3) ;
return df ;

If you really want to call back to R and make a call as you did before, you can do something like this: 

  SEXP call = PROTECT(lang4(install("data.frame"), age, gender, ScalarLogical(FALSE))) ;
  SET_TAG(CDR(call), install("age")) ;
  SET_TAG(CDDR(call), install("gender")) ;
  SET_TAG(CDR(CDDR(call)), install("stringsAsFactors")) ;
  SEXP df = PROTECT(eval(call, R_GlobalEnv)) ;
  UNPROTECT(2) ;
  return df ;

Or you can use Rcpp: 

  DataFrame df = DataFrame::create(
    _["age"] = age, _["gender"] = gender, _["stringsAsFactors"] = FALSE
  ) ;

Romain

Le 3 avr. 2014 à 07:40, Sandip Nandi <sannandi at umail.iu.edu> a écrit :

> Hi ,
> 
> I am asking too many questions , sorry for that .  I am creating a data
> frame in C itself , reading a table .
> 
> The data frame calling code looks like this
> ======================================
> 
> *PROTECT(dfm=lang2(install("data.frame"),df));*
> *SEXP res = PROTECT(eval(dfm,R_GlobalEnv));*
> 
> UNPROTECT(2);
> return res;
> ==================================
> 
> It works fine , now the problem is I want to do the below one  from C
> itself  ( adding the *stringsAsFactors = FALSE* parameter)
> 
> df <- data.frame(gender, age, *stringsAsFactors = FALSE*);
> 
> How can I do it from C , adding extra parameters. Anyone has pointer or any
> example . It will be great help. I find the arguments will always be in
> pair , i don't find any example.
> 
> 
> I try to see the source code ,not able to make it
> 
> Thanks



More information about the R-devel mailing list