Search code examples
rr-markdownlearnr

Randomly take wrong answers of a quiz question from dataframe column, instead of doing by hand


I try to make a kind of learning tool using learnr package. We have one question and for answers where one is the correct one:

Instead of putting in eachtime a wrong answer by hand I would like to take the WRONG answers randomly from the dataframe:

df1 <- tibble(letters = LETTERS, Number = 1:26)

How can I make to take randomly cell values from column Number for answer 1, 2, and 4. The correct answer is answer Nr.3.

In the first step I have tried to use deparse(substitute(df1[1,2])) instead of 1, but failed.

---
title: "Tutorial"
output: learnr::tutorial
runtime: shiny_prerendered
---

```{r setup, include=FALSE}
library(learnr)
library(tidyverse)
knitr::opts_chunk$set(echo = FALSE)
df1 <- tibble(letters = LETTERS, Number = 1:26)
```


Question 1:

```{r quiz}
# This works not
quiz(
  question("Which number has E?",
    answer(deparse(substitute(df1[1,2]))),
    answer(deparse(substitute(df1[4,2]))),
    answer(deparse(substitute(df1[5,2])), correct = TRUE),
    answer(deparse(substitute(df1[8,2])))
  ),
  # This one works
  question("Which number has E?",
    answer("1"),
    answer("4"),
    answer("5", correct = TRUE),
    answer("8")
  )
)
```

output: enter image description here


Solution

  • We need to convert to character class

    ---
    title: "Tutorial"
    output: learnr::tutorial
    runtime: shiny_prerendered
    ---
    
    ```{r setup, include=FALSE}
    library(learnr)
    library(dplyr)    
    knitr::opts_chunk$set(echo = FALSE)
    df1 <- tibble(letters = LETTERS, Number = 1:26)
    ```
    
    
    Question 1:
    
    ```{r quiz}
    # This works not
    quiz(
     question("Which number has E?",
           answer(as.character(df1[[2]][1])),
           answer(as.character(df1[4,2])),
           answer(as.character(df1[5,2]), correct = TRUE),
           answer(as.character(df1[8,2]))         
      ),
      # This one works
      question("Which number has E?",
           answer("1"),
           answer("4"),
           answer("5", correct = TRUE),
           answer("8")
      )
     )
     ```
    

    -output

    enter image description here