【问题标题】:Conditional title heading depending on output of code block R Markdown条件标题标题取决于代码块 R Markdown 的输出
【发布时间】:2020-12-09 23:08:11
【问题描述】:

我知道以前有人问过这个问题,但我仍在努力寻找适合我的示例的答案。基本上,我有这个代码块来读取数据帧的行数。如果数据框中有任何行,它将使用kable() 输出一个表。如果行数为零,则不输出任何表。

当表格是输出时,我想在表格上方有一个标题(只是粗体文本,即"My Table")。当没有表格输出时,我想要没有标题。我怎样才能做到这一点?我尝试在 r 设置块中使用像 print_option 这样的 eval 语句,但没有运气。这是精简后的伪代码:

```{r warning = FALSE, echo = FALSE, fig.height=10, fig.width=6}
    
    #Existing data frame my_df

   numRows <- nrow(my_df)

   if (numRows>0) {

       #Print table 
       my_df %>%
       arrange(my_field)%>%
       kable() %>%  kable_styling(bootstrap_options = "striped","condensed", font_size = 12)

   }


```

【问题讨论】:

  • 您当前的解决方案是否适用于例如 iris 数据集?
  • 感谢您的回复,您的代码确实有效,但我已经编辑了我的问题,因为我没有问正确的问题。对不起!
  • 使用现有代码得到的当前输出是什么?

标签: r r-markdown kable


【解决方案1】:

我对使用 iris 数据集实现您的代码进行了最小的更改,它可以按照您的意愿工作。

没有行(也没有标题)

```{r warning = FALSE, echo = FALSE, fig.height=10, fig.width=6}
library(dplyr)
library(kableExtra)

#Existing data frame my_df
my_df <- iris[NULL, ]
numRows <- nrow(my_df)
```

`r  if (numRows > 0) {"## This is your heading written in markdown"}`

```{r warning = FALSE, echo = FALSE, fig.height=10, fig.width=6}
if (numRows>0) {
  #Print table 
  my_df %>%
    arrange(Species) %>%
    kable() %>%
    kable_styling(bootstrap_options = "striped","condensed", font_size = 12)
}
```

带数据(和表头)

```{r warning = FALSE, echo = FALSE, fig.height=10, fig.width=6}
library(dplyr)
library(kableExtra)

#Existing data frame my_df
my_df <- iris[1:10, ]
numRows <- nrow(my_df)
```

`r  if (numRows > 0) {"## This is your heading written in markdown"}`

```{r warning = FALSE, echo = FALSE, fig.height=10, fig.width=6}
if (numRows>0) {
  #Print table 
  my_df %>%
    arrange(Species) %>%
    kable() %>%
    kable_styling(bootstrap_options = "striped","condensed", font_size = 12)
}
```

【讨论】:

  • 呸,我问错了。我的意思是表格标题 - 标题 - 不是标题。对不起!现在编辑帖子。
  • 我根据您编辑的问题通过注入以下内容更新了答案:r if (numRows &gt; 0) {"## This is your heading written in markdown"}
  • da11an,这行得通,我已经接受了你的回答,谢谢。但它仍然不适用于我在此处重新发布的稍微复杂一点的真实示例:请随时查看并提供答案:stackoverflow.com/questions/65238775/…
猜你喜欢
  • 2017-10-15
  • 2016-04-29
  • 1970-01-01
  • 2019-07-10
  • 2011-11-20
  • 2016-01-13
  • 2017-01-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多