0

I'm trying to use xtable for 3-dimensional array. My minimal example is

Test <- 
structure(1:8, .Dim = c(2L, 2L, 2L), .Dimnames = list(c("A1", 
"A2"), c("B1", "B2"), c("C1", "C2")))

library(plyr)
library(xtable)

a_ply(.data=Test, .margins=3, function(i) {
  xtable(x = Test[, , i])
      }
)

This produces the following error:

  Error in xtable(x = Test[, , i]) : subscript out of bounds

I'd appreciate if you give me some pointers to resolve this problem. Thanks in advance.

MYaseen208
  • 22,666
  • 37
  • 165
  • 309

2 Answers2

4

a_ply doesn't return anything so hopefully your function saves these or something along those lines. the i you're passing to the function is the subset of your array based on the margins you provide. so you're sending it the 2x2 array C1 then the 2x2 array C2:

a_ply(Test, 3, function(i) {print(i); print('-----')})

so indexing into your Test array with i doesn't make sense.

why not just:

apply(Test, 3, xtable)

or using plyr:

alply(Test, 3, xtable)

For knitr:

a_ply(Test, 3, function(i) print(xtable(i)))
Justin
  • 42,475
  • 9
  • 93
  • 111
  • 1
    Almost. They want to include the output using **knitr** so they probably want their function to be `function(x) {print(xtable(x))}` and then use `a_ply` to suppress all other output. – joran Apr 19 '12 at 16:39
  • @Justin: I'd appreciate if you let me know how to include the name of third dimension in the caption of these tables. Like `C1` in the first table's caption and `C2` in the second table's caption. Thanks – MYaseen208 Apr 19 '12 at 17:27
  • `sapply(dimnames(Test)[[3]], function(i) {print(xtable(Test[,,i], caption=i)); return(NULL)})` I don't know `knitr` well, but that makes the latex properly. – Justin Apr 19 '12 at 17:47
  • @Justin: Thanks again for your help. Your given code works fine except giving extra stuff like this `$C1 NULL`. I wonder how to get rid of this. Thanks – MYaseen208 Apr 19 '12 at 18:07
1

This is an old thread, but I had a similar issue on a current project. I wanted an HTML table output with the caption labelled using the name of the 3rd dim of my array.

The problem was overcome by using my array differently. This answer led me to my solution.

x <- 1:dim(Test)[3]
l_ply(x, 
      function(i) cat(print(
                           xtable(Test[,,i],
                                  caption = paste("Heading ",
                                          dimnames(Test)[[3]][i],
                                          sep = "")),
                           type = "html", caption.placement = "top"), 
                         file = "Test.html",
                         append = TRUE))
Community
  • 1
  • 1