[Rd] Characters in lists.

James Bullard bullard at berkeley.edu
Sat Jun 4 22:00:49 CEST 2005

Hi all, this should be a relatively straightforward question. I am 
constructing an R list in C which will contain both Integers and Strings 
(by string I mean in C I have const char* whose values I want passed 
through to R) The Integers are easy. I do something like this:

INTEGER(tmp)[0] = header.GetCols();
SET_STRING_ELT(names, i, mkChar("cols"));
SET_VECTOR_ELT(vals, i++, tmp);

This works just fine. So, when I wanted to set a string element of the 
list (please correct my nomenclature if I am refering to things 
incorrectly) I used the following bit of code:

SET_STRING_ELT(names, i, mkChar("header"));
SET_VECTOR_ELT(vals, i++, mkChar(header.GetHeader().c_str()));

I did this based on the fact that this is how I have created named 
attributes for lists in the past and it seemed to work fine, however in 
R when I call the function I get the following results (sorry for the 
output, but I think the important thing is the <CHARSXP: ...>).

119\rGridCornerUR=5286 153\rGridCornerLR=5253 5270\rGridCornerLL=130 
T1:CLS=5412 RWS=5412 XIN=2  YIN=2  VE=30        2.0 07/09/04 13:38:45 
50101350  M10   \024  \024 Doe16s.1sq \024  \024  \024  \024  \024  
\024  \024  \024  \024 

Ok, so then I thought to try something a little closer to how I did the 
INTEGER. So I used the following code:

CHAR(tmp)[0] = *header.GetHeader().c_str();
SET_STRING_ELT(names, i, mkChar("header"));
SET_VECTOR_ELT(vals, i++, tmp);

Which in R returns the following:

[1] ""

So that is not working. So the question is: given a function in C/C++ 
which returns a const char* how do I correctly create an R character 
string/vector (terminology?) to set as a list element. Thanks for any 
advice or any particular parts of the R source tree which might be 
illuminating. Also, if anyone knows some shorter code for the above code 
which sets the INTEGER elements of the list that would be nice as well.

Thanks in advance, Jim

More information about the R-devel mailing list