Search code examples
rr-exams

Prevent copy & paste of code chunks in R/exams


We currently use R/exams to create exams in our coding course. We found students could easily copy & paste the code chunk and run it without thinking. Example:

output example

We thus wonder if there is an argument/option in R/exam or other packages that could prevent this case, e.g., converting the code chunk into images. Then, the students cannot copy & paste our code.


Solution

  • General comments

    There isn't a readily available option to generate the image but the building blocks are available to write a little bit of code yourself. In particular the R/exams packages provides a tex2image() function which can take a LaTeX code chunk and turn it into an image which you can subsequently embed in the question.

    Worked example

    Below I provide a worked example which also randomly inserts some elements into the code:

    ```{r, include=FALSE}
    ## code as character string
    code <- "
    x <- %s
    
    if (x > %s) {
      x <- x + 1
    } else if (x == %s) {
      x <- x - 1
    } else {
      x <- x * (-1)
    }
    
    x
    "
    
    ## random inputs
    x <- sample(-9:9, 1)
    y <- sample(-3:3, 1)
    code <- sprintf(code, x, y, y)
    
    ## screenshot
    img <- tex2image(c("\\begin{verbatim}", code, "\\end{verbatim}"),
      name = "code", dir = ".", resize = 220)
    
    ## solution
    sol <- eval(parse(text = code))
    ```
    
    Question
    ========
    The following code results in which output?
    \
    ![R code](code.png)
    
    
    Meta-information
    ================
    exname: Conditional execution (with screenshot)
    extype: num
    exsolution: `r sol`
    

    The idea is to first set up the code (or a code template) as a character string, then insert some randomized elements, generate the image, evaluate the code output and then prepare in the usual R/exams way. You might have to play with the resize argument to control the size of the image in a suitable way.

    Further recommendations

    Personally, I'm not fond of such workarounds because they feel like introducing additional hurdles which are not really about learning R. Using these strategies might also incentivize students to find workarounds like using OCR (see the other answers).

    Instead, I usually try to change the answer format to single-choice or multiple-choice, based on qualitative statements. For example, for the code from your original post:

    • For any positive input, one unit is added. [true]
    • If the input is not positive, one unit is substracted. [false]
    • One unit is added to all non-negative inputs. [false]

    And so on...