Seydou GORO
Seydou GORO

Reputation: 1285

KableExtra does not work well with tableby

I'd like to do a contingency table between sex and disease. As I use R.markdown for pdf. reports, I use kableExtra to customize the tables. KableExtra doesn't make the tables well when they are not data.frame. So they make ugly table with tableby

With this data.frame here is what I got.

library(kableExtra)
library(arsenal)
set.seed(0)
Disease<-sample(c(rep("Name of the first category of the disease",20),
rep("Name of the Second category of the disease",32),
rep("Name of the third category of the disease",48),
rep("The category of those who do not belong to the first three categories",13)))
ID<-c(1:length(Disease))
Gender<-rbinom(length(Disease),1,0.55)
Gender<-factor(Gender,levels = c(0,1),labels = c("F","M"))

data<-data.frame(ID,Gender,Disease)

When I run the result of this analysis with R.markdown (pdf) I get this kind of table

enter image description here

There are two problems, thirsly KableExtra:: doesn't deal with the characters &nbsp;&nbsp;&nbsp; Secondly I can't customize columns width when I use tableby with kableExtra, cause I would like to enlarge the column containing variable names, since I am really working with data where the names of the variable values are very long. But if I use kable of knitr::, the characters &nbsp;&nbsp;&nbsp; are removed, but the tables are not scale down, and a part is not displayed. I think knitr has many limitations.

How can I deal with this problem? Or is there another function which could be used in R.markdown (pdf format) to make beautiful contingency table with p.value.

Upvotes: 2

Views: 1323

Answers (1)

kaitlu
kaitlu

Reputation: 36

To avoid the &nbsp;&nbsp;&nbsp; being added to your output when using knitr, use results='asin' in the chunk set up options, so like:

{r results='asis'}

You can control the width of the column with your variable names in them by using the width option in the print function. You technically do not need to wrap the summary call in print, but it doesn't change anything if you do, and you are able to adjust the width setting.

So, for your example:

print(summary(tableby(Gender~Disease)), width = 20)

should make it more readable when it renders to pdf. You can change the width and it will wrap at the limit you set.

Using the code from your example and the above function call, the table looks like this when knit to pdf:

enter image description here

Upvotes: 2

Related Questions