How to conditionally exlude/include a stretch of text that in itself includes inline code?

Viewed 22

I am trying to create an R-markdown document the aim of which is to automate reporting the written exam results in our school. It includes both data visualization for the results (parametrized to take into account the differences between different subjects and exam types).

There is a section in my code the aim of which is to determine how many separate classes the results come from

length(levels(data$class))

and automatically perform either an independent samples t-test or an ANOVA to test for differences between classes, using the overall exam score as the dependent variable.

This part of the code works fine. However, it is followed by a stretch of actual text that I would also like to parametrize to automatically report the results of whatever test has been performed. It uses parameters in the text, like the following:

The results of the `r ifelse(length(levels(fulldata$Osztály)) > 2, "One-way ANOVA", " t-test")` were `r ifelse(p_val > 0.05, "non-significant", "significant")`

This works fine, however, I'm not sure how to handle the case where all results come from a single class. p_val is a global variable created inside the if-statement responsible for choosing the test to perform, and if the results come from a single class, it falls through the logic (since no test is performed) and no p-value is generated, so R throws an error when it gets to the parametrized stretch of text.

Is it possible to make displaying the actual R-Markdown text conditional on an if-statement? I rewrote the entire code using

print(cat(.......))

but it is displayed in the HTML document with a white border, which looks bad, and is inconsistent with the rest of the document. I'm basically looking for something like eval = length(levels(Class)) > 2, only for the text block inside the R-Markdown file. Is this possible to do?

1 Answers

I'd create your text in an R chunk and change it conditional on the levels. In the chunk:

f <- factor(c("a", "a", "a")) # replace with your factor variable 
sentence <- ""
if (length(levels(f)) > 1) {
  p_val <- .01 # and your p-value
  test <- ifelse(length(levels(f)) > 2, "One-way ANOVA", " t-test")
  test_result <- ifelse(p_val > 0.05, "non-significant", "significant")
  sentence <- paste0("The results of the ", test, " were ", test_result, ". ")
}

Then in the text:

Here are the first results. `r sentence`The other results follow.

Which will print, depending on the levels:

Here are the first results. The other results follow.

Here are the first results. The results of the t-test were significant. The other results follow.

Here are the first results. The results of the One-way ANOVA were significant. The other results follow.

Related