From murdoch.duncan at gmail.com  Thu Mar  6 21:10:08 2014
From: murdoch.duncan at gmail.com (Duncan Murdoch)
Date: Thu, 06 Mar 2014 15:10:08 -0500
Subject: [Rd] Create dataframe in C from table and return to R
In-Reply-To: <CAGSjAUC-w9zt5fL0i=R6z6yFyKBT8Dv9bbGsfG7TwBp_GLE9sw@mail.gmail.com>
References: <CAGSjAUC-w9zt5fL0i=R6z6yFyKBT8Dv9bbGsfG7TwBp_GLE9sw@mail.gmail.com>
Message-ID: <5318D620.2000806@gmail.com>

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



[Rd] Create dataframe in C from table and return to R
Duncan Murdoch