On Oct 13, 2011, at 3:20 AM, Alok Jadhav wrote:
> I am a bit confused about usage of R internal functions. I am able to send
a
> char vector from C to R but not sure on how to send a vector of strings
etc.
>
> My code looks like this.
>
> <code>
>
> SEXP result >
PROTECT(Rf_allocMatrix(STRSXP,s->n_rics,s->n_fields));
>
> int i,j;
> for (i=0; i < s->n_rics; i++)
> {
> for (j=0; j < s->n_fields; j++)
> {
> std::string text = s->data[j][i];
> result[j][i] = R_alloc( text.length(), sizeof(char));
> //strcpy(result[j][i], text.c_str());
> SET_STRING_ELT(result[j][i],0,Rf_mkChar(text.c_str()));
> }
> }
>
> //
memcpy(result,s->data.ref(),s->n_fields*s->n_rics*sizeof(200));
> UNPROTECT(1);
> return result;
>
> </code>
>
> Can someone please make me understand this usecase and how to resolve it?
>
It's more simple than that:
int rows = s->n_rics, cols = s->n_fields;
SEXP result = PROTECT(Rf_allocMatrix(STRSXP, rows, cols));
for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++)
SET_STRING_ELT(result, i + j * rows, Rf_mkChar(s->data[j][i].c_str()));
UNPROTECT(1);
return result;
Cheers,
Simon
> thanks,
> Alok
>
> --
> View this message in context:
http://r.789695.n4.nabble.com/how-to-return-a-matrix-of-strings-from-c-to-R-tp3900763p3900763.html
> Sent from the R devel mailing list archive at Nabble.com.
>
> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel
>
>