Matiss Zuravlevs
Matiss Zuravlevs

Reputation: 379

How to prevent loss of kable table?

I'm trying to create simple .pdf document using R-markdown. It should be: text table text table

  library("data.table") # Extension of data frame object functionality, get help with command: library(help = "data.table")
  library(knitr) # Library for displaying tables in markdown

  txtA <- "TEXT A TEXT A"  
  txtB <- "TEXT B TEXT B"

  tabA  <- data.table(High=c(125,250,360),                        
                   Low=c(19,9,36),                   
                   Middle=c(55,70,67))
  n1 <- 1
  n2 <- 1

  if (n1+n2!= 0) {
    if (n1!=0) {
      cat(paste0("\n","**",txtA,"**"))
      kable(tabA) 
    }
    if (n2!=0) {
      cat(paste0("\n","**",txtB,"**"))
      kable(tabA)
    }
  }

However I get text text table. One table is missing. What could be cause of my problem?

Upvotes: 0

Views: 136

Answers (1)

user2974951
user2974951

Reputation: 10375

Add results='asis' in the chunk and put print() around kable().

#```{r, results='asis'}
library("data.table") # Extension of data frame object functionality, get help with command: library(help = "data.table")
library(knitr) # Library for displaying tables in markdown

txtA <- "TEXT A TEXT A"  
txtB <- "TEXT B TEXT B"

tabA  <- data.table(High=c(125,250,360),                        
                 Low=c(19,9,36),                   
                 Middle=c(55,70,67))
n1 <- 1
n2 <- 1

if (n1+n2!= 0) {
  if (n1!=0) {
    cat(paste0("\n","**",txtA,"**"))
    print(kable(tabA))
  }
  if (n2!=0) {
    cat(paste0("\n","**",txtB,"**"))
    print(kable(tabA))
  }
}
#```

Alternatively divide the two kables into two separate chunks.

#```{r}
if (n1+n2!= 0) {
  if (n1!=0) {
    cat(paste0("\n","**",txtA,"**"))
    kable(tabA)
  }
}
#```

#```{r}
if (n1+n2!= 0) {
  if (n2!=0) {
    cat(paste0("\n","**",txtB,"**"))
    kable(tabA)
  }
}
#```

Upvotes: 2

Related Questions