how do i enter heading in a for loop in R Markdown

I Have below code which works fine in R markdown.


```{r setup, include=FALSE}
library(knitr)
opts_chunk$set(echo = FALSE)
```

```{r, echo=FALSE, include= FALSE}
Names<-c("Apple","banana","Orange")
```

# Apple
```{r, echo=FALSE}

  print(Names[1])



```
# banana
```{r, echo=FALSE}

  print(Names[2])
 

```
# Orange
```{r, echo=FALSE}
 
 print(Names[3])
 

```

But I dont want to write 3 chunks just to enter heading in R markdown.

I can write code in one chink as below. But how do i add heading within code chunk in for loop. So every new loop we enter new heading in ouput generated.

```{r, echo=FALSE, include= FALSE}
x=3

for( i in 1:x)
{  
####here i want to insert heading after vry loop in Markdown with value of Names[i]###
  print(Names[i])
  }

```

Thanks for your help

You may find interesting information in the R Markdown Cookbook

This should help you write raw content markdown from R code

Untested:

x=3

for( i in 1:x)
{  
####here i want to insert heading after vry loop in Markdown with value of Names[i]###
  print(paste("#",Names[i]))
  }

I would recommend storing your data in a data frame and printing the data frame as a table instead.

1] "# Apple"

This is printing above in file. And its not taking as heading in R Markdown

I am not sure how that help. data can be in data frame.

Issue is to print Heading in For loop in R markdown.

OK, now I understand what you mean by heading. I don't think it's possible to do that.

But on the other hand, I think the general case of printing sets of text or numbers is better handing with printing data frames or printing html tables with kable, so I stick with my original answer!

This is ABSOLUTELY possible.

Add results asis to the chunk option, needs echo false and include true.

``` {r chunk name, echo=FALSE, include= T, results="asis"}
x=3

for( i in 1:x)
{  
####here i want to insert heading after vry loop in Markdown with value of Names[i]###
  cat(paste("#",Names[i],"\n"))
  }

Use cat instead of print.

Yes this is possible. Look at the example I posted above. The answer is there. You just need to adapt to your usecase.

Did you try adapting the content of the doc already ?

1 Like
---
title: "R Notebook"
output:
  html_document:
    df_print: paged
---

```{r setup, include=FALSE}
library(knitr)
opts_chunk$set(echo = FALSE)
```

```{r, echo=FALSE, include= FALSE}
Names<-c("Apple","banana","Orange")
```

```{r, results='asis'}
for( i in 1:3){
cat("#",Names[i],"\n",Names[i],"\n\n")}
```

Thanks and i dont thnk i need to do include=TRUE. ITs working without that only.

Good stuff
(Include depends on your defaults I think, it will default to T)

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.