1

I analyze survey results regularly and like to use Rmarkdown so I can make nice HTML output of the results.

The surveys can be many questions (like 40), so creating 40 code chunks, with highly repetitive code and headers, can be annoying. And I can easily do this with a loop in R, I think. However, I'm just stuck on how to combine these 2 processes!

This was close -- how to create a loop that includes both a code chunk and text with knitr in R

But in the end, it was just a loop, and not very flexible. So, I couldn't add a figure to question 22 (or whatever).

### Question 1
#### `r key$Question_Text[key$Question=="Q1"][1]`

```{r chunk1}
quest <- "Q1"
# code for question 1
```

### Question 2
#### `r key$Question_Text[key$Question=="Q2"][1]`

```{r chunk2}
quest <- "Q2"
# Identical code for question 2
```

....and so on....

### Question 35
#### `r key$Question_Text[key$Question=="Q35"][1]`

```{r chunk35}
quest <- "Q35"
# Identical code for question 35
```

Because sometimes, a question has a special type of figure or tweak, I want the output to be something I can paste into RMD and make all the changes there. I just want to skip ahead as much as possible... by making all the boring, identical steps, fully automated.

r2evans
  • 141,215
  • 6
  • 77
  • 149
Sarah
  • 65
  • 4
  • I think you can do this with the [`knit_expand` function](https://cran.r-project.org/web/packages/knitr/vignettes/knit_expand.html). – eipi10 Aug 05 '19 at 18:19
  • I could not figure out a way to do it w knit_expand, without having to type everything again, but maybe I just lack creativity. – Sarah Aug 05 '19 at 20:23

1 Answers1

0

make strings that I can refer to in loop

question<-paste(rep("Question",20), 1:20, sep=" ")

qnum<-paste0(rep("Q",20), 1:20, sep="")

quest_text_code <- paste0("#### ","`r key$Question_Text[key$Question==", "\"",qnum[i],'"' ,"][1]`")

chunk <- paste(rep("chunk",20), 1:20, sep="")

use sink() to send to a text file

sink("outfile.txt")

loop and paste and output into the sink

for(i in 1:20){  cat(paste("###", question[i], "\n", "\n", 
              quest_text_code,"\n", "\n",
              "```", "{r ", chunk[i], "}", "\n","\n", 
              "function.dat(", qnum[i], ")","\n", "\n", 
             "function.dat.nr(", qnum[i], ")","\n", "\n", 
              "```", "\n", "\n"))
}

dev.off() # ends sink

After that, I was able to copy to an RMD file and use find and replace on a few glitches (extra leading spaces) I also had trouble adding "" marks with paste.

Sarah
  • 65
  • 4