[Rd] Create dataframe in C from table and return to R
Duncan Murdoch
murdoch.duncan at gmail.com
Thu Mar 6 21:10:08 CET 2014
On 06/03/2014 1:47 PM, Sandip Nandi wrote:
> Hi ,
>
> I am trying to create a dataframe in C and sebd it back to R. Can anyone
> point me to the part of the source code where it is doing , let me explain
> the problem I am having .
>
> --------------------------------------------------------------------
> My simple implementation is like this
>
> SEXP formDF() {
>
> SEXP dfm ,df , dfint , dfStr,lsnm;
> char *ab[3] = {"aa","vv","gy"};
> int sn[3] ={99,89,12};
> char *listnames[2] = {"int","string"};
> int i;
>
>
> PROTECT(df = allocVector(VECSXP,2));
> PROTECT(dfint = allocVector(INTSXP,3));
> PROTECT(dfStr = allocVector(STRSXP,3));
> PROTECT(lsnm = allocVector(STRSXP,2));
>
> SET_STRING_ELT(lsnm,0,mkChar("int"));
> SET_STRING_ELT(lsnm,1,mkChar("string"));
>
> for ( i = 0 ; i < 3; i++ ) {
> SET_STRING_ELT(dfStr,i,mkChar(ab[i]));
> INTEGER(dfint)[i] = sn[i];
> }
> SET_VECTOR_ELT(df,0,dfint);
> SET_VECTOR_ELT(df,1,dfStr);
> setAttrib(df,R_NamesSymbol,lsnm);
> //PROTECT(dfm=LCONS(dfm,list3(dfm,R_MissingArg,mkFalse())));
>
> UNPROTECT(4);
>
> dfm = PROTECT(lang2(install("data.frame"),df));
> SEXP res = PROTECT(eval(dfm,R_GlobalEnv));
>
> UNPROTECT(2)
>
> }
>
> ------------------------------------------------------------------------
> It works fine but i want it the other way
>
> the output is
> print(result)
> int string
> 1 99 aa
> 2 89 vv
> 3 12 gy
>
>
> I want it in transposed . like
>
> dft <- as.data.frame(t(result))
>
> *Can I do the transpose it from C itself ? Which part of code I should look
> a*t .
>
> What My objective ?
>
> *Reading rows of a table and create a dataframe out of it . R is embedded
> in database so cannot call the odbc . Need to implement that part .
> Database gives me API only to get a whole row at once .*
What you are asking for isn't a normal dataframe. Dataframe columns are
vectors all of a type. You want the first row to be a string, the
second row to be an integer. You can't do that with simple atomic
columns, and you probably don't want to mess with the alternative (which
is to have your columns be lists), because no user will know how to deal
with that.
Duncan Murdoch
More information about the R-devel
mailing list