Enrique Enrique - 1 month ago 6
R Question

Kable doesn't print a table inside if..elsif...else statement

I have made this code to print different tables inside if..elsif..else statement with kable.

```{r}
if (sum(df_final2$change)!=0 && nrow(df_final[is.na(df_final$PEH.1),])!=0) {
cat("The new peptides are:\n")
kable(df_peptides_spectra2)
cat("Decreased or increased:\n")
kable(df_final3)
} else if (sum(df_final2$change)==0 && nrow(df_final[is.na(df_final$PEH.1),])!=0) {
cat("The new peptides are:")
kable(df_peptides_spectra2)
cat("The rest peptides are the same.")
} else if (sum(df_final2$change)!=0 && nrow(df_final[is.na(df_final$PEH.1),])==0) {
cat("The are not new peptides:\n")
cat("Decreased or increased:\n")
kable(df_final3)
} else
cat("The number of peptides are the same\n")
```


Using my data frame, the condition that fulfill the conditions is the Option 2, so I expected to have this:

cat("The new peptides are:")
kable(df_peptides_spectra2)
cat("The rest peptides are the same.")


Although, my output is this, without any table. :

The new peptides are:
The rest of peptides are the same.


Do you know any way to fix this? I've tried to add a line break after each print call (R: why kable doesn't print inside a for loop? ) but I've got the same problem.

Here you have a reproducible example:

```{r}



df <- structure(list(ID = structure(c(1L, 2L, 3L, 4L, 5L),
.Label = c("1", "2", "3", "4" ,"5") ),
sequence = structure(c(1L,2L, 3L, 4L, 5L),
.Label = c(" actgat "," atagattg ", " atatagag ", " atggggg ", " atgtagtt "), class = "factor"),
peptides = structure(c(1L, 2L, 3L, 4L, 5L),
.Label = c(" 54 ", " 84 ", " 32 ", " 36 ", "12"),
class = "factor"), n_project = structure(c(1L, 1L, 1L, 1L, 1L),
.Label = " project ", class = "factor")), .Names = c("ID", "sequence", "peptides", "n_project"), class = "data.frame", row.names = c(NA, -5L))



if (0!=0 && (0)!=0) {
cat("The new peptides are:\n")
kable(df)
cat("Decreased or increased:\n")
kable(df)
} else if (10==10 && 2!=0) {
cat("The new peptides are:")
kable(df)
cat("The rest peptides are the same.")
} else if (10!=10 && 2!=0) {
cat("The are not new peptides:\n")
cat("Decreased or increased:\n")
kable(df)
} else
cat("The number of peptides are the same\n")


```

J_F J_F
Answer

In your reproducible example, use print(kable(df)) to show the tables and {r, results = "asis"}.

```{r, results='asis'}

    cat("The new peptides are:\n")
    print(kable(df))
    cat("\n")
    cat("The rest peptides are the same.")

---

enter image description here