Search code examples
rshinylearnr

Is there a way to import questions and answers from a spreadsheet into a learnr quiz?


I am new to R so thank you in advance for your patience.

I would like to create a multiple choice quiz in R using the learnr package (the quiz content is not about r code). I have all of the questions, response options, and correct answers in a spreadsheet. Since my item bank has over 100 items, I will give a simpler example

Stem<-c("stem1", "stem2", "stem3")
OptionA <- c("a1", "a2", "a3")
OptionB<- c("b1", "b2", "b3")
OptionC<- c("c1", "c2", "c3")
Correct<- c("c1", "b2", "a3")

items<-cbind(Stem, OptionA, OptionB, OptionC, Correct)

Currently, the only way I know how to pull in the data from the spreadsheet is like this:


learnr::question(items$Stem[1],
  answer(items$OptionA[1]),
  answer(items$OptionB[1]),
  answer(items$OptonC[1], correct = TRUE),
  answer(items$OptionD[1])
)

however this still requires me to write that chunk of code for each item and manually assign the correct answers. Does anyone know an easier way of doing this, either with learnr or another package?


Solution

  • You can simply loop over the rows of your data or spreadsheet and use a function to set up the questions and save them in a list. My approach uses purrr::map but you a simple for-loop we also do the trick. Try this:

    ---
    title: "Tutorial"
    output: learnr::tutorial
    runtime: shiny_prerendered
    ---
    
    ```{r setup, include=FALSE}
    library(learnr)
    library(dplyr)
    library(purrr)
    knitr::opts_chunk$set(echo = FALSE)
    ```
    
    
    ```{r}
    Stem<-c("stem1", "stem2", "stem3")
    OptionA <- c("a1", "a2", "a3")
    OptionB<- c("b1", "b2", "b3")
    OptionC<- c("c1", "c2", "c3")
    Correct<- c("c1", "b2", "a3")
    
    items<-data.frame(Stem, OptionA, OptionB, OptionC, Correct)
    ```
    
    ## Topic 1
    
    ### Quiz
    
    ```{r quiz}
    make_q <- function(x) {
      question(x$Stem,
               answer(x$OptionA, correct = x$Correct == x$OptionA),
               answer(x$OptionB, correct = x$Correct == x$OptionB),
               answer(x$OptionC, correct = x$Correct == x$OptionC))
    }
    questions <- items %>% 
      split(.$Stem) %>% 
      purrr::map(make_q)
    ```
    
    ```{r}
    quiz(
      questions[[1]],
      questions[[2]],
      questions[[3]])
    ```