Skip to content

Data table in C

3 messages · Tom McCallum, Seth Falcon, Byron Ellis

#
After getting one list done, I am now struggling to form a data frame in C.

I tried to do a list of lists which gives me :

$<NA>
$<NA>[[1]]
[1] "BID"

$<NA>[[2]]
[1] 0.6718

$<NA>[[3]]
[1] 3e+06


$<NA>
$<NA>[[1]]
[1] "BID"

$<NA>[[2]]
[1] 0.6717

$<NA>[[3]]
[1] 5e+06


$<NA>
$<NA>[[1]]
[1] "BID"

$<NA>[[2]]
[1] 0.6717

$<NA>[[3]]
[1] 17200000


and then as.data.frame them in R but this gives me
X0.type X0.price X0.volume X1.type X1.price X1.volume X2.type X2.price
1     BID   0.6723     3e+06     BID   0.6722     5e+06     BID  0.67195
   X2.volume X3.type X3.price X3.volume X4.type X4.price X4.volume X5.type
1  19400000     BID   0.6723     3e+06     BID   0.6722     5e+06     BID
   X5.price X5.volume X6.type X6.price X6.volume X7.type X7.price X7.volume
1   0.6723     3e+06     BID   0.6723     3e+06     BID  0.67195  19400000
   X8.type X8.price X8.volume X9.type X9.price X9.volume X10.type X10.price
1     BID   0.6723     3e+06     BID  0.67215     1e+07      BID    0.6723
   X10.volume X11.type X11.price X11.volume X12.type X12.price X12.volume
1      5e+06      BID   0.67215      1e+07      BID    0.6723      3e+06

and so on.

Is the only way in C to do this or is there a better way of creating a 2  
dimensional data frame with names columns?  I could not find a  
"data.frame" object so I assume one has to use lists but I can't see how  
to get a 3 column list as the example below shows:

   a b d
1 1 4 7
2 2 5 8
3 3 6 9


Tom
#
"Tom McCallum" <tom.mccallum at levelelimited.com> writes:
[snip]
One approach is to return a named list and then turn that into a
data.frame like:

ret <- .Call("yourFunc", ...)
attr(ret, "row.names") <- as.integer(indx)
class(ret) <- "data.frame"

In C, you need to create a list (VECSXP) and a character vector
(STRSXP) for the names and then put the names on the list.

PROTECT(ret = allocVector(VECSXP, N));
PROTECT(retnames = allocVector(STRSXP, N));

/* fill list and names */

SET_NAMES(ret, retnames);

+ seth
#
Data frames are column, not row oriented so you actually want your
list-o-lists to be

$type
[1] "BID" "BID" "BID"

$price
[1] 0.6178 0.6717 0.6717

$volume
[1] 3e+06 3e+06 17200000

so you'd create a VECSXP of length 3 and then three data vectors (also
of length 3 in this case). One STRSXP and two REALSXPs and assign them
into the VECSXP. Also a names attribute for the VECSXP. There are some
other attributes you have to set (the class attribute among other
things) to build a real data frame, but the general structure is like
that.
On 11/17/06, Tom McCallum <tom.mccallum at levelelimited.com> wrote: