如何在R的learnr教程中实现评分并保存为RData格式
Learnr测验评分与本地保存实现方案
实现思路
- 调用
learnr::get_tutorial_state()获取所有题目的作答状态数据 - 编写评分逻辑,统计用户正确作答的题目数量及总分
- 添加Shiny交互按钮,触发评分计算并将结果保存为RData格式文件
修改后的完整代码
--- title: "Quiz" output: learnr::tutorial: progressive: true allow_skip: true language: en: button: nexttopic: Next Question previoustopic: Previous Question runtime: shiny_prerendered ---
library(learnr) library(shiny) knitr::opts_chunk$set(echo = FALSE) # 定义评分计算函数 calculate_score <- function() { # 获取教程状态 state <- get_tutorial_state() # 筛选出题目作答记录(排除非题目项) question_states <- state[grepl("^question_", names(state))] # 统计正确题数 correct_count <- sum(sapply(question_states, function(x) { !is.null(x$correct) && x$correct })) # 返回评分结果 list(total_questions = length(question_states), correct = correct_count, score = correct_count / length(question_states)) } # 添加评分与保存UI fluidRow( column(12, actionButton("save_score", "计算评分并保存结果"), verbatimTextOutput("score_result") ) ) # 触发评分与保存逻辑 observeEvent(input$save_score, { score <- calculate_score() # 显示评分结果 output$score_result <- renderPrint({ cat(sprintf("总题数:%d\n答对题数:%d\n得分:%.2f", score$total_questions, score$correct, score$score)) }) # 保存评分到RData文件 save(score, file = "quiz_score.RData") showNotification("评分已保存为quiz_score.RData", type = "message") })
Question 1
question("Check all that you have NOT done:", answer("installed R on my computer", message = "* Install R"), answer("installed the RStudio IDE", message = "* Install RStudio IDE"), answer("installed the tidyverse R package", message = "* Install Packages"), answer("None of the above. I've done them all.", correct = TRUE, message = "You can skip this tutorial!"), type = "multiple", incorrect = "This tutorial is here to help! To get set up read:" )
Question 2
question("Where do you download R?", answer("www.rstudio.com/download"), answer("[cloud.r-project.org](http://cloud.r-project.org)", correct = TRUE, message = "You can also download R from [cran.r-project.org](http://cran.r-project.org)"), answer("www.r-project.org", message = "Good try, but not exactly. www.r-project.org doesn't provide a download link, but it does provide a link to one the websites above."), answer("www.r.com"), allow_retry = TRUE )
Questions
Some questions to verify that you understand the purposes of various base and recommended R packages:
quiz(caption = "", question("Which package contains functions for installing other R packages?", answer("base"), answer("tools"), answer("utils", correct = TRUE), answer("codetools") ), question("Which of the R packages listed below are used to create plots?", answer("lattice", correct = TRUE), answer("tools"), answer("stats"), answer("grid", correct = TRUE) ) )
关键代码说明
- 评分计算函数:
calculate_score()通过get_tutorial_state()抓取所有题目状态,筛选出题目项后统计正确作答数,最终返回包含总题数、答对题数和得分的列表。 - 交互按钮与保存逻辑:
actionButton触发评分计算,observeEvent监听按钮点击事件,完成评分计算后将结果显示在页面上,并调用save()函数把评分数据保存为quiz_score.RData文件。 - 通知提示:保存完成后通过
showNotification给用户反馈,确认操作成功。
内容的提问来源于stack exchange,提问作者Bonnie Shakes
相关产品推荐
相关产品推荐

