How can I subscript names in a table from kable()?

走远了吗. 提交于 2019-12-07 08:40:41

问题


Given a data.frame A, how can I use subscripted rows and columns names? Eventually I want produce a table through kable() in rmarkdown (output: word document).

A <- data.frame(round(replicate(3, runif(2)),2))
rownames(A) <- c("Hola123", "Hola234")
A

          X1   X2   X3
Hola123 0.47 0.55 0.66
Hola234 0.89 0.45 0.20

How could I make all numbers from row and column names subscripted when creating a table through kable(A)?

I have tried:

rownames(A) <- c(expression(Hola["123"]), expression(Hola["234"]))
names(A) <- c(expression(X["1"]), expression(X["2"]), expression(X["3"]))

But it does not appears subscripted when creating the table through kable() in the .rmd file.


回答1:


To add subscripts in a rmarkdown document, you can embed your text between two tilde: text~sub~. When using function kable, any text in the table is recognized as markdown syntax. So that your rmarkdown code should be:

```{r}
A <- data.frame(round(replicate(3, runif(2)),2))
rownames(A) <- c("Hola~123~", "Hola~234~")
names(A) <- c("X~1~", "X~2~", "X~3~")
knitr::kable(A)
```



回答2:


Just one note about bamphe's response is that the correct code is misspelled. It should be \\textsubscript{}. It is missing the second "t".

And completing the answer, you might choose to use the arguments row.names and col.names inside kable, in this way:

A <- data.frame(round(replicate(3, runif(2)),2))

rownames(A) <- c("Hola\\textsubscript{123}", "Hola\\textsubscript{234}")

knitr::kable(A,
             row.names = T,
             col.names = c("X\\textsubscript{1}", "X\\textsubscript{2}", "X\\textsubscript{3}"),
             escape = F)


来源:https://stackoverflow.com/questions/43322881/how-can-i-subscript-names-in-a-table-from-kable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!