简体   繁体   English

R,Latex和RMarkdown:xtable()的table()输入缺少列和行标签吗?

[英]R, Latex and RMarkdown: table() input for xtable() missing column and row labels?

I am trying to create a pretty LaTeX table where the names of the row and column variables of a table are included when using the xtable library. 我正在尝试创建一个漂亮的LaTeX表,其中在使用xtable库时包含表的行和列变量的名称。

MWE: MWE:

```{r results="asis"}
test <- data.frame(Apples=c(1,2,3), Oranges=c(4,5,6), Watermelons=c(7,8,9))
testxtab <- xtable(with(test,table(Apples,Oranges)))
print(testxtab, comment=FALSE)
```

The result is a LaTeX table that is missing the "Apples" and "Oranges" labels. 结果是缺少“ Apples”和“ Oranges”标签的LaTeX表。 How do I include them? 如何包含它们?

I'm sure you could adapt this to xtable , but here's one approach you can take using pixiedust . 我确定您可以xtable适应xtable ,但这是您可以使用pixiedust采取的一种方法。 (It isn't a very elegant solution, but given the structure of the table object, I'm not sure elegant is an option). (这不是一个非常优雅的解决方案,但是鉴于table对象的结构,我不确定是否可以选择优雅)。

library(pixiedust)
obj <- with(test, table(Apples, Oranges))

dimnames <- names(attr(obj, "dimnames"))

head <- 
  rbind(c("", dimnames[2], rep("", ncol(obj) - 1)),
        c(dimnames[1], colnames(obj))) %>%
  as.data.frame(stringsAsFactors = FALSE)
body <- cbind(rownames(obj), obj) %>%
  as.data.frame(stringsAsFactor = FALSE)

dust(body) %>%
  redust(head, part = "head") %>%
  sprinkle(rows = 1,
           cols = 2:4,
           merge = TRUE,
           part = "head") %>%
  medley_bw() %>%
  sprinkle_print_method("latex")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM