| Title: | Helper Functions for Creating Tutorials |
|---|---|
| Description: | Helper functions for creating, editing, and testing tutorials created with the 'learnr' package. Provides a simple method for allowing students to download their answers to tutorial questions. For examples of its use, see the 'positron.tutorials' and 'r4ds.tutorials' packages. |
| Authors: | David Kane [aut, cre, cph] (ORCID: <https://orcid.org/0000-0002-6660-3934>) |
| Maintainer: | David Kane <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.6.2.9000 |
| Built: | 2026-05-30 20:54:57 UTC |
| Source: | https://github.com/ppbds/tutorial.helpers |
A function which formats the exercise numbers and code chunk
labels correctly. check_current_tutorial() reads in the tutorial
which is in the active editor window in Positron. It determines what
the number of each exercise should be and fixes any mistakes. It
ensures that all code chunk labels are the correct function of the
section title and exercise number.
check_current_tutorial()check_current_tutorial()
This function checks if specified key variables are present in each tibble's "id" column and returns only tibbles that contain all required key variables.
check_key_vars(tibble_list, key_vars, verbose = FALSE)check_key_vars(tibble_list, key_vars, verbose = FALSE)
tibble_list |
A named list of tibbles, each containing an "id" column with question identifiers |
key_vars |
A character vector of key variables to check for |
verbose |
A logical value (TRUE or FALSE) specifying verbosity level. If TRUE, reports tibbles that are removed and why. |
A list of tibbles that contain all required key variables
## Not run: # Create sample data path <- file.path(find.package("tutorial.helpers"), "tests/testthat/fixtures/answers_html") tibble_list <- gather_submissions(path, "stop") result <- check_key_vars(tibble_list, key_vars = c("name", "email")) ## End(Not run)## Not run: # Create sample data path <- file.path(find.package("tutorial.helpers"), "tests/testthat/fixtures/answers_html") tibble_list <- gather_submissions(path, "stop") result <- check_key_vars(tibble_list, key_vars = c("name", "email")) ## End(Not run)
This function filters a list of tibbles based on whether a key variable's value is among the membership values. It first uses check_key_vars() to ensure the key variable exists, then checks membership. Useful for keeping only specific students or participants.
check_membership(tibble_list, key_var, membership, verbose = FALSE)check_membership(tibble_list, key_var, membership, verbose = FALSE)
tibble_list |
A named list of tibbles, each containing an "id" column and an "answer" column |
key_var |
A character string specifying the key variable to check |
membership |
A character vector of allowed values for the key variable |
verbose |
Logical indicating whether to report removed items (default: FALSE) |
A list of tibbles where the key variable exists and its value is in the membership list
## Not run: # Create sample data with student emails path <- file.path(find.package("tutorial.helpers"), "tests/testthat/fixtures/answers_html") tibble_list <- gather_submissions(path, "stop") result <- check_membership(tibble_list, key_var = "email", membership = c("[email protected]", "[email protected]")) ## End(Not run)## Not run: # Create sample data with student emails path <- file.path(find.package("tutorial.helpers"), "tests/testthat/fixtures/answers_html") tibble_list <- gather_submissions(path, "stop") result <- check_membership(tibble_list, key_var = "email", membership = c("[email protected]", "[email protected]")) ## End(Not run)
Checks that tutorials contain required libraries and child documents. The function looks for library() calls and child document inclusions in the tutorial files.
check_tutorial_defaults( tutorial_paths, libraries = c("learnr", "tutorial.helpers"), children = c("info_section", "download_answers") )check_tutorial_defaults( tutorial_paths, libraries = c("learnr", "tutorial.helpers"), children = c("info_section", "download_answers") )
tutorial_paths |
Character vector of the paths to the tutorials to be examined. |
libraries |
Character vector of library names that should be loaded
in the tutorial. The function looks for |
children |
Character vector of child document names (without the .Rmd
extension) that should be included in the tutorial. The function looks
for these in child document inclusion chunks. Default is
|
No return value, called for side effects.
# Check with default requirements check_tutorial_defaults( tutorial_paths = return_tutorial_paths("tutorial.helpers") ) # Check for specific libraries only check_tutorial_defaults( tutorial_paths = return_tutorial_paths("tutorial.helpers"), libraries = c("learnr", "knitr"), children = c("copy_button") )# Check with default requirements check_tutorial_defaults( tutorial_paths = return_tutorial_paths("tutorial.helpers") ) # Check for specific libraries only check_tutorial_defaults( tutorial_paths = return_tutorial_paths("tutorial.helpers"), libraries = c("learnr", "knitr"), children = c("copy_button") )
Determine the code chunk name of a new exercise in a tutorial.
determine_code_chunk_name(file_path = NULL)determine_code_chunk_name(file_path = NULL)
file_path |
Character string of the file path to the tutorial |
The section id of the exercise based on its section
Finds the number of the next exercise in a tutorial
determine_exercise_number(file_path = NULL)determine_exercise_number(file_path = NULL)
file_path |
Character string of the file path to the tutorial |
The next exercise number based on the file argument or the active document.
Downloads all files or filtered files from a public Google Drive folder to a local directory.
download_google_drive( url, path = NULL, title = NULL, overwrite = TRUE, verbose = TRUE )download_google_drive( url, path = NULL, title = NULL, overwrite = TRUE, verbose = TRUE )
url |
Character string. The Google Drive folder URL or ID. Supports standard folder URLs
(e.g., |
path |
Character string or NULL. The local directory path for downloads. If NULL (default), uses the current working directory. If the directory doesn't exist, it will be created. |
title |
Character vector or NULL. Patterns to match against file names for filtering. If provided, only files whose names contain any of these patterns (case-insensitive) are downloaded. If NULL (default), all files are downloaded. |
overwrite |
Logical. If TRUE (default), overwrites existing files. If FALSE, skips files that already exist. |
verbose |
Logical. If TRUE (default), prints detailed progress messages. |
Character string. The path to the directory where files were downloaded.
## Not run: # Download all files to current directory download_google_drive("https://drive.google.com/drive/folders/1Rgxfiw") # Download to a specific directory with filtering download_google_drive( url = "https://drive.google.com/drive/folders/1Rgxfiw", path = "./my_data", title = c("report", ".csv"), overwrite = FALSE ) ## End(Not run)## Not run: # Download all files to current directory download_google_drive("https://drive.google.com/drive/folders/1Rgxfiw") # Download to a specific directory with filtering download_google_drive( url = "https://drive.google.com/drive/folders/1Rgxfiw", path = "./my_data", title = c("report", ".csv"), overwrite = FALSE ) ## End(Not run)
This function processes an R Markdown tutorial file to standardize code chunk labels based on section names and exercise numbers. It also renumbers exercises sequentially within each section and fixes spacing in topic headers.
format_tutorial(file_path)format_tutorial(file_path)
file_path |
Character string. Path to the R Markdown file to process. |
The function applies the following formatting rules:
Topic headers (# headers) have their spacing standardized
Exercises are renumbered sequentially within each section
Code chunks are relabeled according to the pattern: section-name-exercise-number
Chunks with eval = FALSE receive a -hint-N suffix
Chunks with include = FALSE receive a -test suffix
Chunks with label "setup" are not modified
Chunks with the "file" option are not modified
Unlabeled chunks without key options are not modified
All formatted chunks preserve their original options
Content between quadruple backticks ( ) is preserved untouched
Character string containing the formatted R Markdown content.
This function finds and reads HTML/XML files from a local directory or Google Drive folder that match specified patterns. It extracts tables from the files and returns a list of tibbles containing the submission data.
gather_submissions(path, title, keep_loc = NULL, verbose = FALSE)gather_submissions(path, title, keep_loc = NULL, verbose = FALSE)
path |
The path to the local directory containing the HTML/XML files, or a Google Drive folder URL. If it's a Google Drive URL, the function will download the entire folder to a temporary directory. |
title |
A character vector of patterns to match against the file names. Each pattern is processed separately and results are combined. |
keep_loc |
A character string specifying where to save downloaded files (only for Google Drive URLs). If NULL (default), files are downloaded to a temporary directory and deleted after processing. If specified, files are downloaded to this location and kept. |
verbose |
A logical value (TRUE or FALSE) specifying verbosity level. If TRUE, reports files that are removed during processing. |
Google Drive allows for more than one file with the exact same name. If you download files manually ("by hand"), you will get both files but with one of them automatically renamed by your browser. However, if you use the Google Drive functionality in this function, the second file will overwrite the first, potentially resulting in data loss.
A named list of tibbles, where each tibble contains the data from one HTML/XML file that matches any of the specified patterns and has valid table structure.
## Not run: # Find submissions from local directory path <- file.path(find.package("tutorial.helpers"), "tests/testthat/fixtures/answers_html") tibble_list <- gather_submissions(path = path, title = "stop", verbose = TRUE) # Find submissions from Google Drive folder (temporary download) drive_url <- "https://drive.google.com/drive/folders/10do12t0fZsfrIrKePxwjpH8IqBNVO86N" tibble_list <- gather_submissions( path = drive_url, title = c("positron") ) # Find submissions from Google Drive folder (keep files) tibble_list <- gather_submissions( path = drive_url, title = c("introduction"), keep_loc = "temp_file" ) ## End(Not run)## Not run: # Find submissions from local directory path <- file.path(find.package("tutorial.helpers"), "tests/testthat/fixtures/answers_html") tibble_list <- gather_submissions(path = path, title = "stop", verbose = TRUE) # Find submissions from Google Drive folder (temporary download) drive_url <- "https://drive.google.com/drive/folders/10do12t0fZsfrIrKePxwjpH8IqBNVO86N" tibble_list <- gather_submissions( path = drive_url, title = c("positron") ) # Find submissions from Google Drive folder (keep files) tibble_list <- gather_submissions( path = drive_url, title = c("introduction"), keep_loc = "temp_file" ) ## End(Not run)
Grabs information from the learnr session environment, not
directly from the session object itself. Since we are using the session
environment, we currently don't (?) have a way to save the environment and
hence can't test this function.
get_submissions_from_learnr_session(sess)get_submissions_from_learnr_session(sess)
sess |
session object from shiny with learnr |
a list which includes the exercise submissions of tutorial
We define "testing" a tutorial as (successfully) running
render() on it. This function renders all the tutorials provided in
tutorial_paths. There is no check to see if the rendered file looks OK.
If a tutorial fails to render, then an error will be generated which will
propagate to the caller.
knit_tutorials(tutorial_paths)knit_tutorials(tutorial_paths)
tutorial_paths |
Character vector of the paths to the tutorials to be knitted. |
No return value, called for side effects.
## Not run: knit_tutorials(tutorial_paths = return_tutorial_paths("tutorial.helpers")) ## End(Not run)## Not run: knit_tutorials(tutorial_paths = return_tutorial_paths("tutorial.helpers")) ## End(Not run)
When writing tutorials, it is handy to be able to insert the skeleton for a new code exercise or question. Note that the function determines the correct exercise number to use and also adds appropriate code chunk labels, based on the exercise number and section title.
make_exercise(type = "no-answer", file_path = NULL)make_exercise(type = "no-answer", file_path = NULL)
type |
Character of question type. Must be one of "code", "no-answer", or "yes-answer". Abbreviations such as "no", "yes", and "co" are allowed. |
file_path |
Character path to a file. If NULL, the RStudio active document is used, which is the default behavior. An actual file path is used for testing. |
Exercise skeleton corresponding to the type argument.
This function takes a single HTML file or tibble and finds all questions/answers that contain a specified pattern. It returns the question IDs (from the 'id' column) for rows where the answer contains the pattern.
match_questions(x, pattern, ignore.case = TRUE)match_questions(x, pattern, ignore.case = TRUE)
x |
Either a file path to an HTML file or a tibble with 'id' and 'answer'/'data' columns |
pattern |
A character string to search for in the answers |
ignore.case |
Logical; should the search be case-insensitive? (default: TRUE) |
A character vector of question IDs where the answer contains the pattern
## Not run: # Search in an HTML file question_ids <- match_questions("path/to/submission.html", "temperance") # Returns: c("temperance-16", "temperance-19") # Search in a tibble path <- file.path(find.package("tutorial.helpers"), "tests/testthat/fixtures/answers_html") tibble <- gather_submissions(path, title = "stop")[[1]] result <- match_questions(tibble, "http") ## End(Not run)## Not run: # Search in an HTML file question_ids <- match_questions("path/to/submission.html", "temperance") # Returns: c("temperance-16", "temperance-19") # Search in a tibble path <- file.path(find.package("tutorial.helpers"), "tests/testthat/fixtures/answers_html") tibble <- gather_submissions(path, title = "stop")[[1]] result <- match_questions(tibble, "http") ## End(Not run)
This function opens multiple GitHub.io pages in browser tabs, making it easy for teaching fellows to quickly review student webpages. It can accept either a vector of URLs or a tibble/data.frame containing URLs.
open_github_pages( urls, url_var = NULL, label_var = NULL, delay_seconds = 0.5, browser = "default", verbose = FALSE )open_github_pages( urls, url_var = NULL, label_var = NULL, delay_seconds = 0.5, browser = "default", verbose = FALSE )
urls |
Either a character vector of URLs to open, OR a tibble/data.frame containing submission data with a URL column |
url_var |
Character string specifying the column name containing URLs. Required when urls is a tibble/data.frame. Ignored when urls is a character vector. |
label_var |
Character string specifying the column name to use for identifying each submission in verbose output (e.g., "name", "email"). Only used when urls is a tibble/data.frame. |
delay_seconds |
Numeric value specifying delay between opening each URL (default is 0.5 seconds to allow browser to process each request) |
browser |
Character string specifying which browser to use. Options are "default" (system default), "chrome", "firefox", "safari", or "edge". On Windows, also supports "msedge". Default is "default". |
verbose |
Logical value (TRUE or FALSE) specifying verbosity level. If TRUE, reports each URL as it's being opened. |
The function uses the system's default method to open URLs, which typically opens them in the default browser. Most modern browsers will open multiple URLs as tabs in the same window when called in quick succession.
The delay between opening URLs helps ensure the browser has time to process each request properly. You may need to adjust this delay based on your system performance and browser behavior.
Invisible NULL. Function is called for its side effect of opening browser tabs.
## Not run: # Open multiple GitHub Pages from vector student_sites <- c("https://github.com/Abdul-Hannan96/stops.git") open_github_pages(student_sites, verbose = TRUE) # Open from tibble/data.frame path <- file.path(find.package("tutorial.helpers"), "tests/testthat/fixtures/answers_html") result <- submissions_answers( path = path, title = c("stop"), key_var = "email", membership = c("[email protected]", "[email protected]"), vars = c("name","email","temperance-15"), verbose = TRUE ) open_github_pages(result, url_var = "temperance-15", verbose = TRUE) ## End(Not run)## Not run: # Open multiple GitHub Pages from vector student_sites <- c("https://github.com/Abdul-Hannan96/stops.git") open_github_pages(student_sites, verbose = TRUE) # Open from tibble/data.frame path <- file.path(find.package("tutorial.helpers"), "tests/testthat/fixtures/answers_html") result <- submissions_answers( path = path, title = c("stop"), key_var = "email", membership = c("[email protected]", "[email protected]"), vars = c("name","email","temperance-15"), verbose = TRUE ) open_github_pages(result, url_var = "temperance-15", verbose = TRUE) ## End(Not run)
Takes a package name and returns a character vector of all the paths to tutorials in the installed package. This function looks for all R Markdown files (.Rmd) in the inst/tutorials/ subdirectories of the specified package. It uses learnr::available_tutorials() to identify tutorial directories, with a fallback to directory scanning if that fails.
return_tutorial_paths(package)return_tutorial_paths(package)
package |
Character string of the package name to be tested. |
The function first checks if the package is installed and has a tutorials directory. It then attempts to use learnr::available_tutorials() to get the official list of tutorial directories. If that fails (e.g., if the package doesn't properly register its tutorials with learnr), it falls back to scanning all subdirectories under inst/tutorials/. Finally, it collects all .Rmd files from these directories.
Returns an empty character vector if the package has no tutorials or doesn't exist, rather than throwing an error.
Character vector of the full paths to all installed tutorials in
package. Returns character(0) if no tutorials are found or if the
package doesn't exist.
## Not run: # Get all learnr tutorial paths return_tutorial_paths('learnr') # Get tutorial paths from your own package return_tutorial_paths('tutorial.helpers') # Returns empty vector for packages without tutorials return_tutorial_paths('base') ## End(Not run)## Not run: # Get all learnr tutorial paths return_tutorial_paths('learnr') # Get tutorial paths from your own package return_tutorial_paths('tutorial.helpers') # Returns empty vector for packages without tutorials return_tutorial_paths('base') ## End(Not run)
Locates or creates the Positron settings.json file on Windows or macOS,
then updates those settings based on the provided configuration list.
Users can specify settings like RStudio keyboard shortcuts. The function can
also optionally configure R profile settings including binary package
preferences and download timeout. Positron is an R-focused Integrated Development
Environment (IDE) based on Visual Studio Code, designed to enhance the R programming
experience with a modern interface and features.
set_positron_settings( home_dir = path.expand("~"), set.rprofile = TRUE, positron_settings = list(editor.wordWrap = "on", workbench.startupEditor = "none", files.defaultLanguage = "r", workbench.editor.enablePreview = FALSE, terminal.integrated.defaultProfile.windows = "Git Bash", git.enableSmartCommit = TRUE, git.confirmSync = FALSE) )set_positron_settings( home_dir = path.expand("~"), set.rprofile = TRUE, positron_settings = list(editor.wordWrap = "on", workbench.startupEditor = "none", files.defaultLanguage = "r", workbench.editor.enablePreview = FALSE, terminal.integrated.defaultProfile.windows = "Git Bash", git.enableSmartCommit = TRUE, git.confirmSync = FALSE) )
home_dir |
Optional character string specifying the base directory to use
as the user's home directory. Defaults to |
set.rprofile |
Logical, defaults to |
positron_settings |
List of settings to apply. Can be structured as a list of
lists where each sub-list contains a setting name and value (e.g.,
|
This function uses the jsonlite package to handle JSON operations and
creates the necessary directory structure if it doesn't exist. It is
designed to work cross-platform by detecting the operating system and
constructing the appropriate file path to Positron's user settings. The
function applies the settings provided in the positron_settings parameter.
If the positron_settings list is empty, no changes are made to the settings.json file.
By default, seven settings are applied unless overridden: enabling word wrap for better
code readability, disabling startup editor for a clean interface, setting R as the
default language for new files, disabling preview mode for predictable tab behavior,
setting Git Bash as the default terminal on Windows, enabling Git smart commit,
and disabling Git sync confirmation dialogs.
Note: Windows file paths in settings should use forward slashes (/) or escaped backslashes (\\). The function will automatically handle path normalization for Windows.
Invisible NULL. The function's purpose is its side effect: modifying
or creating the settings.json file. It also prints messages to the console
indicating actions taken.
## Not run: # Apply default settings (word wrap, clean startup, R language, # no preview, Git Bash terminal, smart commit, no sync confirmation) set_positron_settings() # Enable RStudio keyboard shortcuts using list of lists structure set_positron_settings( positron_settings = list(list("rstudio.keymap.enable", TRUE)) ) # Enable RStudio keyboard shortcuts using named list structure set_positron_settings( positron_settings = list("rstudio.keymap.enable" = TRUE) ) # Apply multiple settings using named list set_positron_settings( positron_settings = list( "rstudio.keymap.enable" = TRUE, "editor.wordWrap" = "on" ) ) # Set a Windows file path (use forward slashes) set_positron_settings( positron_settings = list( "files.dialog.defaultPath" = "C:/Users/username/projects" ) ) # Apply settings without modifying .Rprofile set_positron_settings( set.rprofile = FALSE, positron_settings = list("rstudio.keymap.enable" = TRUE) ) # Handle case where settings directory does not exist set_positron_settings( home_dir = tempfile(), # Simulate a non-existent directory positron_settings = list("rstudio.keymap.enable" = TRUE) ) # Handle case with invalid JSON file # Create an invalid JSON file for testing dir.create(file.path(tempdir(), "Positron", "User"), recursive = TRUE) writeLines("invalid json", file.path(tempdir(), "Positron", "User", "settings.json")) set_positron_settings( home_dir = tempdir(), positron_settings = list("rstudio.keymap.enable" = TRUE) ) ## End(Not run)## Not run: # Apply default settings (word wrap, clean startup, R language, # no preview, Git Bash terminal, smart commit, no sync confirmation) set_positron_settings() # Enable RStudio keyboard shortcuts using list of lists structure set_positron_settings( positron_settings = list(list("rstudio.keymap.enable", TRUE)) ) # Enable RStudio keyboard shortcuts using named list structure set_positron_settings( positron_settings = list("rstudio.keymap.enable" = TRUE) ) # Apply multiple settings using named list set_positron_settings( positron_settings = list( "rstudio.keymap.enable" = TRUE, "editor.wordWrap" = "on" ) ) # Set a Windows file path (use forward slashes) set_positron_settings( positron_settings = list( "files.dialog.defaultPath" = "C:/Users/username/projects" ) ) # Apply settings without modifying .Rprofile set_positron_settings( set.rprofile = FALSE, positron_settings = list("rstudio.keymap.enable" = TRUE) ) # Handle case where settings directory does not exist set_positron_settings( home_dir = tempfile(), # Simulate a non-existent directory positron_settings = list("rstudio.keymap.enable" = TRUE) ) # Handle case with invalid JSON file # Create an invalid JSON file for testing dir.create(file.path(tempdir(), "Positron", "User"), recursive = TRUE) writeLines("invalid json", file.path(tempdir(), "Positron", "User", "settings.json")) set_positron_settings( home_dir = tempdir(), positron_settings = list("rstudio.keymap.enable" = TRUE) ) ## End(Not run)
Configures important settings in your .Rprofile to improve the R
experience, especially for new users. This includes:
Setting package installation to use binaries (non-Linux systems)
Increasing the timeout for downloads to prevent installation failures
These settings help avoid common issues like source compilation failures on Windows and timeout errors when downloading large packages.
You can examine your .Rprofile to confirm changes with
usethis::edit_r_profile()
set_rprofile_settings(set_for_session = TRUE, backup = TRUE)set_rprofile_settings(set_for_session = TRUE, backup = TRUE)
set_for_session |
Logical, defaults to |
backup |
Logical, defaults to |
Invisible NULL. Called for side effects.
## Not run: # Apply settings to .Rprofile and current session set_rprofile_settings() # Only modify .Rprofile, don't change current session set_rprofile_settings(set_for_session = FALSE) # Modify without creating backup set_rprofile_settings(backup = FALSE) ## End(Not run)## Not run: # Apply settings to .Rprofile and current session set_rprofile_settings() # Only modify .Rprofile, don't change current session set_rprofile_settings(set_for_session = FALSE) # Modify without creating backup set_rprofile_settings(backup = FALSE) ## End(Not run)
This function reads the contents of a text file and either prints the specified range of rows that match a given regular expression pattern, prints the code lines within R code chunks, or extracts the YAML header. If start is a negative number, it prints the last abs(start) lines, ignoring missing lines at the end of the file. If start is 0, it prints the entire file.
show_file(path, start = 1, end = NULL, pattern = NULL, chunk = "None")show_file(path, start = 1, end = NULL, pattern = NULL, chunk = "None")
path |
A character vector representing the path to the text file. |
start |
An integer specifying the starting row number (inclusive) to consider. Default is 1. If negative, it represents the number of lines to print from the end of the file. If 0, prints the entire file. |
end |
An integer specifying the ending row number (inclusive) to consider. Default is the last row. |
pattern |
A regular expression pattern to match against each row. Default is NULL (no pattern matching). |
chunk |
A character string indicating what content to extract. Possible values are "None" (default - no chunk processing), "All" (print all R code chunks), "Last" (print only the last R code chunk), or "YAML" (extract the YAML header without delimiters). |
The function prints the contents of the specified range of rows that match the pattern (if provided), the code lines within R code chunks (if chunk is "All" or "Last"), or the YAML header content (if chunk is "YAML") to the console. If no rows match the pattern, nothing is printed. If start is negative, the function prints the last abs(start) lines, ignoring missing lines at the end of the file. If start is 0, the function prints the entire file.
## Not run: # Display all rows of a text file show_file("path/to/your/file.txt") # Display the entire file show_file("path/to/your/file.txt", start = 0) # Display rows 5 to 10 of a text file show_file("path/to/your/file.txt", start = 5, end = 10) # Display all rows of a text file that contain the word "example" show_file("path/to/your/file.txt", pattern = "example") # Print all code lines within R code chunks show_file("path/to/your/file.txt", chunk = "All") # Print only the last R code chunk show_file("path/to/your/file.txt", chunk = "Last") # Extract the YAML header show_file("path/to/your/file.Rmd", chunk = "YAML") # Display the last 5 lines of a text file, ignoring missing lines at the end show_file("path/to/your/file.txt", start = -5) ## End(Not run)## Not run: # Display all rows of a text file show_file("path/to/your/file.txt") # Display the entire file show_file("path/to/your/file.txt", start = 0) # Display rows 5 to 10 of a text file show_file("path/to/your/file.txt", start = 5, end = 10) # Display all rows of a text file that contain the word "example" show_file("path/to/your/file.txt", pattern = "example") # Print all code lines within R code chunks show_file("path/to/your/file.txt", chunk = "All") # Print only the last R code chunk show_file("path/to/your/file.txt", chunk = "Last") # Extract the YAML header show_file("path/to/your/file.Rmd", chunk = "YAML") # Display the last 5 lines of a text file, ignoring missing lines at the end show_file("path/to/your/file.txt", start = -5) ## End(Not run)
Provides the core Shiny server and UI hooks for collecting and downloading student answers
from a learnr tutorial. submission_server() should be called in an Rmd code chunk with
context="server".
This function was modified from Colin Rundel's learnrhash package (https://github.com/rundel/learnrhash).
UI block to include a download button and simple instructions for students.
submission_server() submission_uisubmission_server() submission_ui
An object of class shiny.tag of length 3.
The server function uses a Shiny downloadHandler to let students download their answers.
All main logic must be wrapped in local() with parent.frame() to ensure access to the live
learnr session and objects created in the parent environment.
The session object (created by Shiny) is only available inside the downloadHandler$content
function, so any test-case extraction or answer writing must happen there.
For reference: the file argument in content is a temporary file path created by Shiny,
and your handler's job is to write the downloadable file there.
If you want to generate test fixtures, insert browser() inside the content function,
then use functions like get_submissions_from_learnr_session(session) at the prompt.
See also: https://mastering-shiny.org/action-transfer.html#downloading-reports
No return value; called for side effects in a Shiny/learnr session.
An object of class shiny.tag
if(interactive()){ submission_server() } if(interactive()){ submission_ui }if(interactive()){ submission_server() } if(interactive()){ submission_ui }
This function gathers submissions matching a title pattern, filters them by membership, and extracts specified variables, returning a tibble with one row per valid submission and one column per variable.
submissions_answers( path, title, key_var = NULL, membership = NULL, vars, keep_file_name = NULL, verbose = FALSE )submissions_answers( path, title, key_var = NULL, membership = NULL, vars, keep_file_name = NULL, verbose = FALSE )
path |
The path to the local directory or Google Drive folder URL containing submissions |
title |
A character vector of patterns to match against file names (passed to gather_submissions) |
key_var |
A character string specifying the key variable to check for membership (e.g., "email"). If NULL (default), no membership filtering is applied. |
membership |
A character vector of allowed values for the key variable, or "*" to include all submissions. If NULL (default), no membership filtering is applied. Ignored if key_var is NULL. |
vars |
A character vector of variables/questions to extract, or "*" to extract all available variables |
keep_file_name |
How to handle file names: NULL (don't include), "All" (full name), "Space" (up to first space), "Underscore" (up to first underscore) |
verbose |
A logical value (TRUE or FALSE) specifying verbosity level. If TRUE, reports files that are removed during processing. |
A tibble with one row per valid submission, columns for each variable, and optionally a "source" column
## Not run: # Extract specific variables from submissions matching title pattern path <- file.path(find.package("tutorial.helpers"), "tests/testthat/fixtures/answers_html") result <- submissions_answers( path = path, title = c("stop"), key_var = "email", membership = c("[email protected]", "[email protected]"), vars = c("name", "email", "introduction-1"), verbose = TRUE ) # Extract all variables from submissions result_all <- submissions_answers( path = path, title = c("stop"), key_var = "email", membership = c("[email protected]", "[email protected]"), vars = "*", verbose = TRUE ) drive_url <- "https://drive.google.com/drive/folders/10do12t0fZsfrIrKePxwjpH8IqBNVO86N" x <- submissions_answers( path = drive_url, title = c("introduction"), key_var = "email", membership = c("[email protected]"), vars = c("email", "name", "what-you-will-learn-15") ) ## End(Not run)## Not run: # Extract specific variables from submissions matching title pattern path <- file.path(find.package("tutorial.helpers"), "tests/testthat/fixtures/answers_html") result <- submissions_answers( path = path, title = c("stop"), key_var = "email", membership = c("[email protected]", "[email protected]"), vars = c("name", "email", "introduction-1"), verbose = TRUE ) # Extract all variables from submissions result_all <- submissions_answers( path = path, title = c("stop"), key_var = "email", membership = c("[email protected]", "[email protected]"), vars = "*", verbose = TRUE ) drive_url <- "https://drive.google.com/drive/folders/10do12t0fZsfrIrKePxwjpH8IqBNVO86N" x <- submissions_answers( path = drive_url, title = c("introduction"), key_var = "email", membership = c("[email protected]"), vars = c("email", "name", "what-you-will-learn-15") ) ## End(Not run)
This function processes submissions from a local directory or Google Drive folder containing HTML/XML files. It extracts tables from the files, filters them based on a pattern and key variables, and returns either a summary tibble or a combined tibble with all the data.
submissions_summary( path, title = ".", return_value = "Summary", vars = NULL, verbose = FALSE, keep_file_name = NULL, emails = NULL )submissions_summary( path, title = ".", return_value = "Summary", vars = NULL, verbose = FALSE, keep_file_name = NULL, emails = NULL )
path |
The path to the local directory containing the HTML/XML files, or a Google Drive folder URL. If it's a Google Drive URL, the function will download individual files to a temporary directory. |
title |
A character vector of patterns to match against the file names (default: "."). Each pattern is processed separately and results are combined. |
return_value |
The type of value to return. Allowed values are "Summary" (default) or "All". |
vars |
A character vector of key variables to extract from the "id" column (default: NULL). |
verbose |
A logical value (TRUE or FALSE) specifying verbosity level. If TRUE, reports files that are removed during processing. |
keep_file_name |
Specifies whether to keep the file name in the summary tibble. Allowed values are NULL (default), "All" (keep entire file name), "Space" (keep up to first space), or "Underscore" (keep up to first underscore). Only used when |
emails |
A character vector of email addresses to filter results by, "*" to include all emails, or NULL to skip email filtering (default: NULL). |
If return_value is "Summary", returns a tibble with one row for each file, columns corresponding to the vars,
and an additional "answers" column indicating the number of rows in each tibble.
If return_value is "All", returns a tibble with all the data combined from all the files.
## Not run: # Process submissions from local directory path <- file.path(find.package("tutorial.helpers"), "tests/testthat/fixtures/answers_html") result <- submissions_summary(path = path, vars = "email", title = "stop") drive_url <- "https://drive.google.com/drive/folders/10do12t0fZsfrIrKePxwjpH8IqBNVO86N" x <- submissions_summary( path = drive_url, title = c("positron"), vars = c("email", "name") ) ## End(Not run)## Not run: # Process submissions from local directory path <- file.path(find.package("tutorial.helpers"), "tests/testthat/fixtures/answers_html") result <- submissions_summary(path = path, vars = "email", title = "stop") drive_url <- "https://drive.google.com/drive/folders/10do12t0fZsfrIrKePxwjpH8IqBNVO86N" x <- submissions_summary( path = drive_url, title = c("positron"), vars = c("email", "name") ) ## End(Not run)
Take a tutorial session (or a submission list), extract all submitted answers, and write out an HTML file with those answers.
write_answers(file, obj)write_answers(file, obj)
file |
Output file path (should end in .html). |
obj |
Either a Shiny session object (from learnr) or a list of submissions (as returned by get_submissions_from_learnr_session()). |