### Install ggplot2 Package Source: https://docs.posit.co/ide/user/ide/get-started Installs the ggplot2 R package, which is necessary for creating data visualizations. This command only needs to be run once. ```R install.packages("ggplot2") ``` -------------------------------- ### Install addinexamples Package Source: https://docs.posit.co/ide/user/ide/guide/productivity/add-ins Installs the 'addinexamples' package from GitHub, which provides example RStudio addins. This is often a prerequisite for exploring and developing addins. ```R # if necessary: install.packages("devtools") devtools::install_github("rstudio/addinexamples", type = "source") ``` -------------------------------- ### Example: Using an RStudio Addin command Source: https://docs.posit.co/ide/user/ide/guide/ui/command-palette Demonstrates searching for a command provided by an installed RStudio Addin, using the 'styler' addin as an example. ```text styler format ``` -------------------------------- ### Start RStudio with a Specific R Version using rig Source: https://docs.posit.co/ide/user/ide/guide/environments/r/managing-r This command starts RStudio, connecting it to a specified R version managed by the 'rig' tool. Ensure 'rig' is installed and the desired R version is available on your system. This is a command-line utility. ```bash rig rstudio 4.3.0 ``` -------------------------------- ### Load ggplot2 Package Source: https://docs.posit.co/ide/user/ide/get-started Loads the ggplot2 R package into the current R session, making its functions available for use. This command needs to be run every time a new R session starts. ```R library(ggplot2) ``` -------------------------------- ### Install ptexamples Package Source: https://docs.posit.co/ide/user/ide/guide/productivity/project-templates Installs the 'ptexamples' package from GitHub, which is used to demonstrate RStudio project templates. It requires the 'devtools' package to be installed first. ```R # if needed install.packages("devtools") devtools::install_github("rstudio/ptexamples") ``` -------------------------------- ### Install rsconnect R Package Source: https://docs.posit.co/ide/user/ide/guide/publish/connecting Installs the 'rsconnect' R package, which is necessary for publishing R content to Posit Connect, Shinyapps.io, and RPubs. Includes instructions for installing the development version from GitHub. ```r install.packages("rsconnect") # or the development version from GitHub # install.packages("devtools") # devtools::install_github("rstudio/rsconnect") ``` -------------------------------- ### Install Shiny and miniUI Packages Source: https://docs.posit.co/ide/user/ide/guide/productivity/add-ins Command to install the necessary R packages, 'shiny' and 'miniUI', which are required for developing Shiny Gadgets. ```r install.packages(c("shiny", "miniUI")) ``` -------------------------------- ### Initialize an empty renv project Source: https://docs.posit.co/ide/user/ide/guide/environments/r/renv Initializes a project with an empty private library, allowing manual package installation. This is useful when you prefer to manage project dependencies yourself. ```r renv::init(bare = TRUE) ``` -------------------------------- ### Initialize a new renv project Source: https://docs.posit.co/ide/user/ide/guide/environments/r/renv Initializes a new project-local environment with a private R library. It discovers project dependencies and installs them using renv::hydrate(). It also sets up the project's .Rprofile for automatic library loading. ```r renv::init() ``` -------------------------------- ### Initialize Git Repository with `git init` Source: https://docs.posit.co/ide/user/ide/guide/code/projects This command initializes a new Git repository in the project's root directory. It's used when no version control is set up and you want to start using Git. ```shell git init ``` -------------------------------- ### Install rstudioapi Package Source: https://docs.posit.co/ide/user/ide/guide/productivity/add-ins Installs the 'rstudioapi' package, which provides functions to interact with and manipulate RStudio's environment, documents, and user interface from R code. ```R install.packages("rstudioapi") ``` -------------------------------- ### Check R Installation Path in R Console Source: https://docs.posit.co/ide/user/ide/guide/troubleshooting/desktop-will-not-start Verify if RStudio can locate your R installation by checking the system's PATH environment variable. This command is executed within an R console session. ```r > Sys.which("R") ``` -------------------------------- ### Shiny Gadget UI Definition with miniUI Source: https://docs.posit.co/ide/user/ide/guide/productivity/add-ins Example of defining the User Interface (UI) for a Shiny Gadget using the 'miniUI' package. It demonstrates creating a title bar and a content panel. ```r ui <- miniPage( gadgetTitleBar("My Gadget"), miniContentPanel( ## Your UI items go here. ) ) ``` -------------------------------- ### Install R Package Development Tools Source: https://docs.posit.co/ide/user/ide/guide/pkg-devel/writing-packages Installs essential R packages for package development, including devtools, roxygen2, testthat, and knitr. Ensure you have the necessary build tools and LaTeX installed on your system. ```r install.packages(c("devtools", "roxygen2", "testthat", "knitr")) ``` -------------------------------- ### RStudio Addin Registration (addins.dcf) Source: https://docs.posit.co/ide/user/ide/guide/productivity/add-ins Example of an `addins.dcf` file format for registering an RStudio addin. This file specifies the addin's name, a brief description, the R function to bind it to, and whether it's interactive. ```r Name: Insert %in% Description: Inserts `%in%` at the cursor position. Binding: insertInAddin Interactive: false ``` -------------------------------- ### Install Plumber and Rapidoc Packages Source: https://docs.posit.co/ide/user/ide/guide/tools/jobs-in-action Installs the 'plumber' and 'rapidoc' R packages from CRAN. These packages are necessary for creating and documenting Plumber APIs. ```r install.packages(c("plumber", "rapidoc")) ``` -------------------------------- ### Get R_HOME Path Source: https://docs.posit.co/ide/user/ide/guide/environments/r/managing-r This R command retrieves the R_HOME directory path, which is necessary for locating the `Rprofile.site` and `Renviron.site` files specific to a particular R version. ```r R.home(component = "home") ``` -------------------------------- ### RStudio Snippet Definition Example Source: https://docs.posit.co/ide/user/ide/guide/productivity/custom-settings Provides an example of how to define a custom R snippet for calling an R library, to be placed in the RStudio snippets directory. ```r # ~/.config/rstudio/snippets on Mac/Linux # AppData/Roaming/RStudio/snippets on Windows snippet lib library(${1:package})__ ``` -------------------------------- ### Example: Finding a command in RStudio Command Palette Source: https://docs.posit.co/ide/user/ide/guide/ui/command-palette Illustrates how to search for a command, such as creating a new script, by typing a partial command name into the palette. ```text new scr ``` -------------------------------- ### Initial File Comments for Copilot Guidance Source: https://docs.posit.co/ide/user/ide/guide/tools/copilot Provides an example of using initial file comments to set the context for Copilot. These comments outline the script's purpose, dependencies, and any constraints, helping Copilot generate more relevant and accurate code suggestions. ```R # This script will do x # using the packages x,y,z # other constraints or details__ ``` -------------------------------- ### Shiny Gadget Server Logic Source: https://docs.posit.co/ide/user/ide/guide/productivity/add-ins Example of a server function for a Shiny Gadget. It includes placeholder for reactive logic and an observer to handle the 'done' event, which is crucial for closing the gadget after user interaction. ```r server <- function(input, output, session) { ## Your reactive logic goes here. # Listen for the 'done' event. This event will be fired when a user # is finished interacting with your application, and clicks the 'done' # button. observeEvent(input$done, { # Here is where your Shiny application might now go and affect the # contents of a document open in RStudio, using the `rstudioapi` package. # # At the end, your application should call 'stopApp()' here, to ensure that # the gadget is closed after 'done' is clicked. stopApp() }) } ``` -------------------------------- ### RStudio: Clean and Install R Package Source: https://docs.posit.co/ide/user/ide/guide/pkg-devel/writing-packages Rebuilds and reinstalls an R package in a fresh R session. It unloads the existing version, installs the package using 'R CMD INSTALL', restarts the R session, and reloads the package with the 'library' function. ```R library(package_name) ``` -------------------------------- ### Basic R Connection Snippet Source: https://docs.posit.co/ide/user/ide/guide/data/connection-snippets Initializes a connection by loading the readr library and reading a CSV file. This is a fundamental example of a connection snippet. ```R library(readr) data <- read_csv(readr_example("mtcars.csv")) ``` -------------------------------- ### Query a Plumber API using httr GET Source: https://docs.posit.co/ide/user/ide/guide/tools/jobs-in-action Demonstrates how to send a GET request to a running Plumber API's '/echo' endpoint using the 'httr' package and retrieve the content. ```r get_echo <- httr::GET("http://127.0.0.1:6285/echo", query = list(msg = "dog")) httr::content(get_echo) ``` -------------------------------- ### Save ggplot to file in R Source: https://docs.posit.co/ide/user/ide/get-started Saves the ggplot object 'mpg_plot' to a PNG file named 'my-first-plot.png' with specified dimensions. This allows for exporting the visualization for reports or presentations. ```R ggsave("my-first-plot.png", plot = mpg_plot, height = 4, width = 6) ``` -------------------------------- ### View mpg dataset interactively in R Source: https://docs.posit.co/ide/user/ide/get-started Opens the 'mpg' dataframe in a new tab within the RStudio Source pane, allowing for interactive exploration. This is an alternative to the console output for viewing data. ```R View(mpg) ``` -------------------------------- ### Install MLOps Packages for Vetiver Source: https://docs.posit.co/ide/user/ide/guide/tools/jobs-in-action Installs necessary R packages for MLOps tasks, including 'tidymodels', 'vetiver', 'pins', and 'plumber' from CRAN. ```r install.packages(c("tidymodels", "vetiver", "pins", "plumber")) ``` -------------------------------- ### Basic Text Insertion Addin Example Source: https://docs.posit.co/ide/user/ide/guide/productivity/add-ins Demonstrates a simple RStudio addin that inserts the text ' %in% ' at the current cursor position. This is a fundamental example of a text macro addin. ```R insertInAddin <- function() { rstudioapi::insertText(" %in% ") } ``` -------------------------------- ### Install Quarto R Package Source: https://docs.posit.co/ide/user/ide/guide/documents/quarto-project Command to install the 'quarto' R package using the R console, which is necessary for rendering Quarto documents from R. ```r install.packages("quarto") ``` -------------------------------- ### Install reticulate R Package from GitHub (R) Source: https://docs.posit.co/ide/user/ide/guide/environments/py/python Instructions for installing the development version of the reticulate R package from GitHub using devtools. ```r # If needed, install.packages("devtools") devtools::install_github("rstudio/reticulate") ``` -------------------------------- ### Hydrate project library with renv Source: https://docs.posit.co/ide/user/ide/guide/environments/r/renv Installs discovered packages into the project library. It optimizes by copying packages from the user library when possible, rather than reinstalling from CRAN. ```r renv::hydrate() ``` -------------------------------- ### Display first few rows of mpg dataset in R Source: https://docs.posit.co/ide/user/ide/get-started Displays the first six rows of the 'mpg' dataframe. This function is useful for a quick overview of the data structure and content. ```R head(mpg) ``` -------------------------------- ### RStudio Default Document Template Example Source: https://docs.posit.co/ide/user/ide/guide/productivity/custom-settings Demonstrates how to create a default template for R scripts to include a standard comment header, to be placed in the templates directory. ```r # ~/.config/rstudio/templates on Mac/Linux # AppData/Roaming/RStudio/templates on Windows # ------------------------------------- # Script: # Author: # Purpose: # Notes: # # Copyright(c) Corporation Name # -------------------------------------__ ``` -------------------------------- ### Print ggplot to output pane in R Source: https://docs.posit.co/ide/user/ide/get-started Prints the previously created ggplot object ('mpg_plot') to the R output pane, specifically within the 'Plots' tab. This displays the generated visualization. ```R mpg_plot ``` -------------------------------- ### Assign mpg dataset in R Source: https://docs.posit.co/ide/user/ide/get-started Temporarily assigns the 'mpg' dataset, built into ggplot2, to an object named 'mpg' in the current R session. This allows for data manipulation and visualization. ```R # this will temporarily assign the mpg dataset # to the mpg object in our current session mpg <- ggplot2::mpg ``` -------------------------------- ### Convert and Add a .tmTheme File to RStudio Source: https://docs.posit.co/ide/user/ide/guide/ui/appearance Converts a .tmTheme file and adds it to RStudio. It allows specifying whether to add the converted theme, an output location for a copy, applying it immediately, forcing the operation, and installing it globally or for the current user. ```r rstudioapi::convertTheme(themePath, add = TRUE, outputLocation = NULL, apply = FALSE, force = FALSE, globally = FALSE) ``` -------------------------------- ### Create a scatter plot with linear model in R Source: https://docs.posit.co/ide/user/ide/get-started Generates a scatter plot using ggplot2, mapping engine size ('displ') to the x-axis and highway fuel efficiency ('hwy') to the y-axis. It adds points colored by car class and a linear model smooth line. The plot is assigned to the 'mpg_plot' object. ```R mpg_plot <- ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) + geom_point(mapping = aes(colour = class)) + geom_smooth(method = "lm", formula = "y ~ x") ``` -------------------------------- ### Custom Snippet Definition Example (setMethod) Source: https://docs.posit.co/ide/user/ide/guide/productivity/snippets An example of a custom snippet definition for 'setMethod'. It uses variables defined with {variable_name} for interactive editing. A literal '$' must be escaped as '\$'. ```text snippet sm setMethod("${1:gen}", ${2:"class"}, function(${3:obj}, ...) { ${0} }) ``` -------------------------------- ### R Code Section Creation Examples Source: https://docs.posit.co/ide/user/ide/guide/code/code-sections Demonstrates various comment formats recognized by RStudio IDE to automatically create foldable code sections. These sections help in organizing code into logical blocks for easier navigation and management. ```r # Section One --------------------------------- # Section One ---- # Section Two ================================= # Section Two ==== ### Section Three ############################# ### Section Three #### ``` -------------------------------- ### Connecting to a Database in R using odbc package Source: https://docs.posit.co/ide/user/ide/guide/data/data-connections This snippet demonstrates how to establish a database connection in R using the 'odbc' package. It assumes the 'odbc' package is installed and configured. The code enables navigation of database hierarchies and allows for closing connections. ```r library(odbc) # Example: Connect to a database using a DSN con <- dbConnect(odbc(), "YourDSNName") # Navigate database structure dbListTables(con) # Preview table data head(dbReadTable(con, "your_table_name")) # Close the connection dbDisconnect(con) ``` -------------------------------- ### Generate a Function to Square a Number (R) Source: https://docs.posit.co/ide/user/ide/guide/tools/copilot Illustrates how a simple inline comment can guide Copilot to generate a basic R function. This demonstrates Copilot's utility for generating small, self-contained code blocks based on natural language prompts. ```R # create a function that takes a number and returns the square__ ``` ```R # create a function that takes a number and returns the square square_number <- function(x) { x^2 }__ ``` -------------------------------- ### R Connection Snippet with Keyed Parameters Source: https://docs.posit.co/ide/user/ide/guide/data/connection-snippets Demonstrates creating a semicolon-separated list of values using the ${Position:Label=Default:Key} syntax, commonly used for database connections. Includes examples of escaping special characters like ':' and '='. ```R "${2:Letters=ABC:LettersKey}${3:Numbers=123:NumbersKey}" ``` -------------------------------- ### Create a Function to Calculate Standard Error (R) Source: https://docs.posit.co/ide/user/ide/guide/tools/copilot Shows how to use comments to prompt Copilot to generate a specific R function. This example includes type checking and handling missing values, demonstrating Copilot's ability to create robust code based on detailed instructions. ```R # Create a robust function to calculate the standard error of a vector # The function name will be calc_se with an argument x for the vector, with # an argument to remove missing values called na.rm, and a default value of TRUE # The function should have type checking to only allow numeric vectors__ ``` ```R calc_se <- function(x, na.rm = TRUE) { if (!is.numeric(x)) { stop("x must be numeric") } if (na.rm) { x <- x[!is.na(x)] } sqrt(var(x) / length(x)) }__ ``` ```R calc_se(1:10) #> [1] 0.9574 # note the function also properly indicates the need for a numeric input calc_se(letters) #> Error in calc_se(letters) : x must be numeric__ ``` -------------------------------- ### Get Current Theme Information Source: https://docs.posit.co/ide/user/ide/guide/ui/appearance Retrieves information about the currently active RStudio theme, including its name and whether it's a dark theme. ```APIDOC ## GET /rstudioapi/getThemeInfo ### Description Retrieves information about the currently active RStudio theme. ### Method GET ### Endpoint rstudioapi::getThemeInfo() ### Response #### Success Response (200) - **editor** (string) - The name of the editor theme. - **global** (string) - The name of the global theme. - **dark** (boolean) - Indicates if the theme is dark. #### Response Example ```json { "editor": "Xcode", "global": "Modern", "dark": true } ``` ``` -------------------------------- ### R: List Objects and Preview Data in Connections Pane Source: https://docs.posit.co/ide/user/ide/guide/data/connection-contracts Provides examples of R functions used by RStudio to list objects within a connection and preview their data. These functions (`listObjects`, `previewObject`) accept an object specifier to navigate the connection's structure. ```r listObjects() ## returns all schema listObjects(schema = "foo") ## returns tables and views in "foo" previewObject(schema = "foo", ## returns data in foo.bar table = "bar") ``` -------------------------------- ### Quarto Document with Jupyter Engine Configuration Source: https://docs.posit.co/ide/user/ide/guide/documents/quarto-project An example of a Quarto markdown file configured to use the Jupyter engine. It includes YAML front matter specifying the 'jupyter' kernel as 'python3'. ```yaml --- title: "Matplotlib Demo" author: "Norah Smith" jupyter: python3 --- ``` -------------------------------- ### Add an .rstheme File to RStudio Source: https://docs.posit.co/ide/user/ide/guide/ui/appearance Adds a new theme to RStudio from a specified .rstheme file. Allows control over applying the theme immediately, forcing the add operation if a duplicate exists, and installing it globally or for the current user. ```r rstudioapi::addTheme(themePath, apply = FALSE, force = FALSE, globally = FALSE) ``` -------------------------------- ### Quarto Knitr Code Chunk with Options Source: https://docs.posit.co/ide/user/ide/guide/documents/quarto-project An example of an R code chunk in a Quarto document using the Knitr engine. It demonstrates how to specify chunk options like 'echo' and 'fig-cap' using special comments at the top of the chunk. ```r ```{r} #| echo: false #| fig-cap: "Air Quality" library(ggplot2) ggplot(airquality, aes(Temp, Ozone)) + geom_point() + geom_smooth(method = "loess", se = FALSE) ``` ``` -------------------------------- ### Configure Proxy Server for GitHub Copilot in RStudio Source: https://docs.posit.co/ide/user/ide/guide/tools/copilot This configuration allows GitHub Copilot to use an enterprise's internal proxy server. It can be set either in the rsession.conf file for server-based RStudio installations or as an environment variable for RStudio Desktop. ```INI copilot-proxy-url= ``` ```R Sys.setenv("COPILOT_PROXY_URL" = "") ``` -------------------------------- ### Generate RStudio Diagnostic Report (Windows) Source: https://docs.posit.co/ide/user/ide/guide/troubleshooting/diagnostic-report Executes RStudio with the --run-diagnostics flag to generate a diagnostic report on Windows. This command is used when RStudio is not starting or for manual troubleshooting. The report is saved in the user's Documents directory. ```shell "C:\\Program Files\\RStudio\\rstudio.exe" --run-diagnostics__ ``` -------------------------------- ### Edit .Renviron File with usethis Source: https://docs.posit.co/ide/user/ide/guide/environments/r/managing-r The `usethis` R package provides a convenient function, `usethis::edit_r_environ()`, to open and edit either the user-level or project-level `.Renviron` file directly from an R session. ```r usethis::edit_r_environ() ``` -------------------------------- ### Define hello_world Project Template Function Source: https://docs.posit.co/ide/user/ide/guide/productivity/project-templates Defines the 'hello_world' function intended for use as an RStudio project template. This function creates a directory, generates a header with input information, and writes it to an 'INDEX' file within the new project path. ```R hello_world <- function(path, ...) { # ensure path exists dir.create(path, recursive = TRUE, showWarnings = FALSE) # generate header for file header <- c( "# This file was generated by a call to 'ptexamples::hello_world()'.", "# The following inputs were received:", "" ) # collect inputs and paste together as 'Parameter: Value' dots <- list(...) text <- lapply(seq_along(dots), function(i) { key <- names(dots)[[i]] val <- dots[[i]] paste0(key, ": ", val) }) # collect into single text string contents <- paste( paste(header, collapse = "\n"), paste(text, collapse = "\n"), sep = "\n" ) # write to index file writeLines(contents, con = file.path(path, "INDEX")) } ``` -------------------------------- ### Configure Custom SSL Certificates for GitHub Copilot in RStudio Source: https://docs.posit.co/ide/user/ide/guide/tools/copilot This configuration enables GitHub Copilot to use custom SSL certificates, which is necessary in environments with specific security requirements. The setting is applied in the rsession.conf file for server installations, mirroring the functionality of the NODE_EXTRA_CA_CERTS environment variable. ```INI copilot-ssl-certificates-file= ``` -------------------------------- ### Customizing RStudio Terminal and UI Elements with CSS Source: https://docs.posit.co/ide/user/ide/guide/ui/appearance This snippet outlines CSS selectors for customizing RStudio's terminal pane and other UI elements not directly related to the code editor. It highlights selectors starting with `.terminal`, `.xterm`, and theme-specific prefixes like `rstheme_` for safe customization. ```css Selectors for the Terminal pane typically include `.terminal` or selectors that begin with `.xterm`. Classes used to modify parts of RStudio unrelated to the editor are prefixed with `rstheme_`, with exceptions like `dataGridHeader` and `themedPopupPanel`. Classes not prefixed with `rstheme_`, `ace_`, or explicitly listed are subject to change and unsafe for custom themes. ``` -------------------------------- ### Add Standard Error Calculation to R Code (dplyr) Source: https://docs.posit.co/ide/user/ide/guide/tools/copilot Shows how to use an inline comment within a dplyr pipeline to prompt Copilot for a specific calculation. This example highlights how Copilot can assist in modifying or extending existing code blocks by understanding the context provided by comments. ```R library(dplyr) mtcars |> group_by(cyl) |> summarize( mean = mean(mpg), # add the standard error for mpg )__ ``` ```R library(dplyr) mtcars |> group_by(cyl) |> summarize( mean = mean(mpg), # add the standard error for mpg se = sd(mpg) / sqrt(n()) )__ ``` -------------------------------- ### Create a New R Package Source: https://docs.posit.co/ide/user/ide/guide/pkg-devel/writing-packages Demonstrates how to create a new R package using the usethis package. This function initializes a new package structure and prepares it for development. ```r usethis::create_package() ``` -------------------------------- ### Run a Plumber API Locally with Rapidoc Source: https://docs.posit.co/ide/user/ide/guide/tools/jobs-in-action Sets up and runs a Plumber API locally. It configures Rapidoc for interactive documentation and displays it in the RStudio Viewer pane. Requires 'plumber.R' to exist. ```r library(plumber) library(rapidoc) pr("plumber.R") %>% pr_set_docs("rapidoc") %>% pr_set_docs_callback(rstudioapi::viewer) %>% pr_run() ``` -------------------------------- ### Install reticulate R Package from CRAN (R) Source: https://docs.posit.co/ide/user/ide/guide/environments/py/python Command to install the latest stable version of the reticulate R package from CRAN. ```r install.packages("reticulate") ``` -------------------------------- ### Live Preview Quarto Project with R Package Source: https://docs.posit.co/ide/user/ide/guide/documents/quarto-project R code to initiate a live preview for a Quarto website or book project by calling 'quarto_preview()' on the project directory. ```r library(quarto) quarto_preview() ``` -------------------------------- ### Configure R Startup Options and Variables Source: https://docs.posit.co/ide/user/ide/guide/environments/r/managing-r The .Rprofile file allows execution of R code upon startup, enabling the configuration of options and environment variables. This includes setting package repository locations and customizing session behaviors like output width for interactive sessions. Environment variables must be set using Sys.setenv(). ```r options(repos = c(CRAN = "https://packagemanager.posit.co/all/latest")) if (interactive()) { options(width = 120) } ``` -------------------------------- ### Launch Vetiver API Directly Source: https://docs.posit.co/ide/user/ide/guide/tools/jobs-in-action This R code demonstrates launching a vetiver API directly without explicitly writing a Plumber file. It assumes a 'vetiver_model' object named 'v' exists in the global environment and sets up the API to use it, with documentation linked to the RStudio viewer. ```r pr() %>% pr_set_docs_callback(rstudioapi::viewer) %>% # use the existing vetiver_model object 'v' vetiver_api(v) %>% pr_run() ``` -------------------------------- ### Edit .Rprofile File with usethis Source: https://docs.posit.co/ide/user/ide/guide/environments/r/managing-r The `usethis` R package offers a helper function, `usethis::edit_r_profile()`, to easily edit the user or project `.Rprofile` file from within an R session. ```r usethis::edit_r_profile() ``` -------------------------------- ### Include Additional Files in YAML Header (R Markdown/Quarto) Source: https://docs.posit.co/ide/user/ide/guide/publish/publishing Demonstrates how to specify additional files to be included in the deployment bundle using the `resource_files` field in the YAML header of an R Markdown or Quarto document. This is useful when files are not directly referenced in the document but are required for rendering. ```yaml --- output: html_document resource_files: - data/my_data.csv - scripts/helper_function.R --- This is the main content of the document. ``` -------------------------------- ### Using recover() for Debugging R Markdown Errors Source: https://docs.posit.co/ide/user/ide/guide/code/debugging To facilitate debugging when errors occur in R Markdown documents, you can configure R's error handling to call `recover()` and `sink()`. This setup, placed in the R Markdown setup block, ensures that when an error happens, the sink is removed, and `recover()` is invoked, allowing you to inspect the call stack and variables at the point of failure. ```r options(error = function() { sink() recover() }) ``` -------------------------------- ### RStudio Keybindings Configuration Paths Source: https://docs.posit.co/ide/user/ide/guide/productivity/custom-settings Lists the file paths for defining custom editor and RStudio command keybindings on macOS/Linux and Windows. ```text # Mac or Linux ~/.config/rstudio/keybindings/editor_commands.json ~/.config/rstudio/keybindings/rstudio_commands.json # Windows AppData/Roaming/RStudio/keybindings/editor_commands.json AppData/Roaming/RStudio/keybindings/rstudio_commands.json__ ``` -------------------------------- ### Set Custom Python Path in R (R) Source: https://docs.posit.co/ide/user/ide/guide/environments/py/python How to specify a custom Python installation path for RStudio by setting an R option. ```r options(rstudio.python.installationPath = "/path/to/python") ``` -------------------------------- ### Ask Copilot Questions with Comments Source: https://docs.posit.co/ide/user/ide/guide/tools/copilot Demonstrates how to ask Copilot questions using a specific comment format. Copilot responds with an answer in a designated comment format. This is useful for quick information retrieval within the development environment. ```R # q: What is the definition of standard error?__ ``` ```R # q: What is the definition of standard error? # a: The standard error is the standard deviation of the sampling distribution of a statistic.__ ``` -------------------------------- ### Access R Function Help using ? and help() Source: https://docs.posit.co/ide/user/ide/guide/ui/ui-panes Demonstrates how to access the help documentation for a specific R function using either the '?' operator or the 'help()' function. This is a fundamental way to learn about R functions and their usage. ```r ?paste0() # or help(paste0) ``` -------------------------------- ### Query a Plumber API using httr POST Source: https://docs.posit.co/ide/user/ide/guide/tools/jobs-in-action Demonstrates how to send a POST request to a running Plumber API's '/sum' endpoint using the 'httr' package and retrieve the content. ```r post_sum <- httr::POST("http://127.0.0.1:6285/sum", query = list(a=1, b = 2)) httr::content(post_sum) ``` -------------------------------- ### Include Environment Variables with rsconnect (R) Source: https://docs.posit.co/ide/user/ide/guide/publish/publishing Shows how to programmatically include environment variables when publishing content using the `rsconnect` R package. This is a secure way to manage secrets like API keys or passwords, as they are sent over an encrypted connection and not stored in the deployment bundle. ```r library(rsconnect) # Deploy a Shiny app, including environment variables deplyApp(appDir = "./my_shiny_app", appName = "my_app_name", account = "my_account", server = "connect.posit.co", envVars = c("MY_API_KEY", "DATABASE_URL")) # Deploy an R Markdown document, including environment variables # Note: rsconnect::deployDoc might not directly support envVars in the same way as deployApp # Consult rsconnect documentation for specific Rmd deployment methods if needed. # deployDoc(file = "my_document.Rmd", appName = "my_doc_name", account = "my_account") ``` -------------------------------- ### Run Plumber API with Vetiver Model Locally Source: https://docs.posit.co/ide/user/ide/guide/tools/jobs-in-action This R script sets up and runs a Plumber API to serve a vetiver model locally. It uses the 'plumber' and 'vetiver' libraries to define the API and specify how to run it, directing documentation to the RStudio viewer. ```r library(plumber) library(vetiver) pr("vetiver-plumber.R") %>% pr_set_docs_callback(rstudioapi::viewer) %>% pr_run() ``` -------------------------------- ### Get Current RStudio Theme Information Source: https://docs.posit.co/ide/user/ide/guide/ui/appearance Retrieves information about the currently active RStudio theme. This function is useful for customizing package output to match user-selected themes. ```r rstudioapi::getThemeInfo() ``` -------------------------------- ### File Input Widget Configuration Source: https://docs.posit.co/ide/user/ide/guide/productivity/project-templates Configures a file input for a project template parameter, allowing the user to select a file from their disk. ```text Parameter: file Widget: FileInput Label: Data file__ ``` -------------------------------- ### Heading Creation Shortcuts Source: https://docs.posit.co/ide/user/ide/guide/documents/visual-editor Demonstrates markdown shortcuts for creating different levels of headings directly within the Quarto visual editor. ```Markdown # ``` ```Markdown ## ``` ```Markdown ### ``` -------------------------------- ### Text Input Widget Configuration Source: https://docs.posit.co/ide/user/ide/guide/productivity/project-templates Sets up a text input field for a project template parameter, accepting free-form text from the user. ```text Parameter: author Widget: TextInput Label: Author__ ``` -------------------------------- ### R: Provide R style diagnostics (e.g. whitespace) Source: https://docs.posit.co/ide/user/ide/guide/code/diagnostics This diagnostic checks if R code conforms to Hadley Wickham's style guide, specifically focusing on whitespace usage. Currently, this feature is not user-configurable. ```R # Example of code that might trigger a style diagnostic (e.g., incorrect whitespace) my_vector <- c(1,2, 3) ``` -------------------------------- ### RStudio Themes Directory Path Source: https://docs.posit.co/ide/user/ide/guide/productivity/custom-settings Specifies the directory where custom RStudio color theme files (.rstheme) should be placed on macOS/Linux and Windows. ```text # Mac or Linux ~/.config/rstudio/themes # Windows AppData/Roaming/RStudio/themes__ ``` -------------------------------- ### RStudio Configuration Directory Paths Source: https://docs.posit.co/ide/user/ide/guide/productivity/custom-settings Specifies the default user-level configuration directory paths for RStudio on macOS/Linux and Windows systems. ```text # Mac or Linux, user level ~/.config/rstudio/ # Windows AppData/Roaming/RStudio/__ ``` -------------------------------- ### Train and Deploy Vetiver Model to Plumber API Source: https://docs.posit.co/ide/user/ide/guide/tools/jobs-in-action Trains a decision tree model using 'tidymodels', saves it as a 'vetiver' model pin, and then writes out this model as a Plumber API. ```r library(tidymodels) library(vetiver) library(pins) car_mod <- workflow(mpg ~ ., decision_tree(mode = "regression")) %>% fit(mtcars) v <- vetiver_model(car_mod, "cars_mpg") model_board <- board_folder("pins-r", versioned = TRUE) model_board %>% vetiver_pin_write(v) # write out a vetiver model to a plumber API vetiver_write_plumber(model_board, "cars_mpg", file = "vetiver-plumber.R") ``` -------------------------------- ### Select Input Widget Configuration Source: https://docs.posit.co/ide/user/ide/guide/productivity/project-templates Defines a select input for a project template parameter, allowing users to choose from a list of options. 'Fields' specifies the available choices. ```text Parameter: project_type Widget: SelectInput Label: Project Type Fields: project, package__ ``` -------------------------------- ### R: Warn if variable is defined but not used Source: https://docs.posit.co/ide/user/ide/guide/code/diagnostics This diagnostic helps identify variables that are created but never utilized in the code. It's useful for code cleanup and debugging. The example shows a variable 'result' being assigned but not used, with the sum being re-computed and returned instead. ```R result <- sum(1:10) # The variable 'result' is defined but not used. sum(1:5) ``` -------------------------------- ### Convert and Add tmTheme Source: https://docs.posit.co/ide/user/ide/guide/ui/appearance Converts a tmTheme file and optionally adds it to RStudio, applies it, and saves a copy. ```APIDOC ## POST /rstudioapi/convertTheme ### Description Converts a tmTheme file and optionally adds it to RStudio. ### Method POST ### Endpoint rstudioapi::convertTheme(themePath, add, outputLocation, apply, force, globally) ### Parameters #### Path Parameters - **themePath** (string) - Required - A full or relative path to the tmTheme file to add. #### Query Parameters - **add** (boolean) - Optional - Whether to add the converted theme to RStudio immediately. Default: `TRUE`. - **outputLocation** (string) - Optional - A full or relative path where an additional copy of the converted theme will be saved. If this value is not set and `add` is set to `FALSE`, no file will be saved. Default: `NULL`. - **apply** (boolean) - Optional - Whether to immediately apply the newly added theme. Default: `FALSE`. - **force** (boolean) - Optional - Whether to force the add operation if a file with the same name already exists. Default: `FALSE`. - **globally** (boolean) - Optional - Whether to add the theme for all users (`TRUE`) or the current user (`FALSE`). Default: `FALSE`. ### Response #### Success Response (200) - **themeName** (string) - The name of the newly added theme. #### Response Example ```json { "themeName": "MyConvertedTheme" } ``` ``` -------------------------------- ### Generate RStudio Diagnostic Report (Linux) Source: https://docs.posit.co/ide/user/ide/guide/troubleshooting/diagnostic-report Initiates RStudio with the --run-diagnostics flag via the Terminal on Linux to produce a diagnostic report. This command is employed when RStudio encounters startup issues. The diagnostic report is stored in the user's home directory. ```shell rstudio --run-diagnostics__ ``` -------------------------------- ### Generate HTML and JavaScript Counter from HTML Comments Source: https://docs.posit.co/ide/user/ide/guide/tools/copilot Demonstrates how Copilot can interpret HTML comments within a Quarto document to generate functional HTML and JavaScript code for a clickable counter with a reset button. This highlights Copilot's ability to understand context and generate complex UI elements from simple instructions. ```html

Click the button to count clicks.

Clicks: 0

``` -------------------------------- ### List All Available RStudio Themes Source: https://docs.posit.co/ide/user/ide/guide/ui/appearance Retrieves a list of all themes currently available in RStudio, including built-in and custom themes. The output format includes the theme's name and whether it is a dark theme. ```r rstudioapi::getThemes() ``` -------------------------------- ### R: Check arguments to R function calls Source: https://docs.posit.co/ide/user/ide/guide/code/diagnostics This diagnostic checks if function calls have correct arguments. It detects missing, unmatched, partially matched, and too many arguments, even if the function is not defined in the current scope. The example demonstrates detecting a missing 'y' argument in an 'add_numbers' function call. ```R add_numbers(x) ``` -------------------------------- ### Live Preview Quarto Document with R Package Source: https://docs.posit.co/ide/user/ide/guide/documents/quarto-project R code to initiate a live preview of a Quarto document ('document.qmd') using the 'quarto_preview' function. This function automatically renders and refreshes the browser on save. ```r library(quarto) quarto_preview("document.qmd") ``` -------------------------------- ### tmTheme Scopes for RStudio Source: https://docs.posit.co/ide/user/ide/guide/ui/appearance A table detailing the scopes supported by RStudio for custom tmTheme files and their impact on syntax highlighting in the IDE. ```markdown | comment | Changes the color and style of comments. | |---|---| | constant | Changes the color and style of constants like `TRUE`, `FALSE`, and numeric literals. | | constant.language | Changes the color and style of language constants like `TRUE` and `FALSE`. This value will override the settings in the “constant” scope for language constants, if set. Also in R Markdown files, everything surrounded in `*`. | | constant.numeric | Changes the color and style of numeric literals. This value will override the settings in the “constant” scope for numeric literals, if set. Also in R Markdown files, everything surrounded in `**`. | | keyword | Changes the color and style of keywords like `function`, `if`, `else`, `stop`, and operators. | | keyword.operator | Changes the color and style of operators like `(`, `)`, `=`, `+`, and `-`. This value will override the settings in the “keyword” scope for operators, if set. | | marker-layer.active_debug_line | Changes the color and style of the highlighting on the line of code which is currently being debugged. | | markup.heading | Changes the color and style of the characters that start a heading in R Markdown documents. | | meta.tag | Changes the color and style of metadata tags in R Markdown documents, like `title`. | | string | Changes the color and style of string literals. | | support.function | Changes the color and style of code blocks in R Markdown documents. | ``` -------------------------------- ### Define .Renviron Key-Value Pairs Source: https://docs.posit.co/ide/user/ide/guide/environments/r/managing-r The .Renviron file uses a simple key-value format to define environment variables. These variables can be accessed within an R session using Sys.getenv(). This file is useful for storing sensitive information like API keys or configuring R-specific settings such as history size and library locations. ```text Key1=value1 Key2=value2 ...additional key=value pairs__ ``` -------------------------------- ### RStudio User Preferences File Path Source: https://docs.posit.co/ide/user/ide/guide/productivity/custom-settings Indicates the location of the rstudio-prefs.json file, which stores user preferences configurable through the Global Options dialog. ```text # Mac or Linux, user level ~/.config/rstudio/rstudio-prefs.json # Windows AppData/Roaming/RStudio/rstudio-prefs.json__ ``` -------------------------------- ### Restore project state with renv Source: https://docs.posit.co/ide/user/ide/guide/environments/r/renv Reverts the project's package library to the state recorded in the renv.lock file. This is useful if updating packages introduces problems. ```r renv::restore() ``` -------------------------------- ### Preview Object Data Source: https://docs.posit.co/ide/user/ide/guide/data/connection-contracts Details how to retrieve a preview of data from an object using the `previewObject` function. ```APIDOC ## GET /connection/objects/preview ### Description Retrieves a specified number of rows from a data object for previewing. Requires an object specifier and a row limit. ### Method GET ### Endpoint /connection/objects/preview ### Parameters #### Query Parameters - **objectSpecifier** (object) - Required - A set of named arguments corresponding to the object types, specifying the data object to preview. - **rowLimit** (integer) - Required - The maximum number of rows to return. ### Response #### Success Response (200) - **dataPreview** (data.frame) - A data frame containing the previewed data. ### Response Example ```json { "dataPreview": [ { "column1": 1, "column2": "A" }, { "column1": 2, "column2": "B" } ] } ``` ### Request Example GET /connection/objects/preview?schema=schema1&table=table1&rowLimit=10 ``` -------------------------------- ### Show Command Palette Shortcut Source: https://docs.posit.co/ide/user/ide/reference/shortcuts Provides shortcuts to display the Command Palette, a feature for quick access to all program commands. This includes variations for different browsers and operating systems. ```General Ctrl+Shift+P, Ctrl+Alt+Shift+P (Firefox) | Shift+Command+P ``` -------------------------------- ### List Columns of an Object Source: https://docs.posit.co/ide/user/ide/guide/data/connection-contracts Explains how to list columns for a specific data object using the `listColumns` function. ```APIDOC ## GET /connection/objects/columns ### Description Lists the columns of a specified data object within a connection. Requires an object specifier to identify the target object. ### Method GET ### Endpoint /connection/objects/columns ### Parameters #### Query Parameters - **objectSpecifier** (object) - Required - A set of named arguments corresponding to the object types, specifying the data object whose columns are to be listed. ### Response #### Success Response (200) - **columns** (data.frame) - A data frame with `name` and `type` columns for each column in the object. ### Response Example ```json { "columns": [ { "name": "column1", "type": "integer" }, { "name": "column2", "type": "character" } ] } ``` ### Request Example GET /connection/objects/columns?schema=schema1&table=table1 ``` -------------------------------- ### List Available Themes Source: https://docs.posit.co/ide/user/ide/guide/ui/appearance Retrieves a list of all available editor themes in RStudio, including their names and whether they are dark themes. ```APIDOC ## GET /rstudioapi/getThemes ### Description Retrieves a list of all available editor themes in RStudio. ### Method GET ### Endpoint rstudioapi::getThemes() ### Response #### Success Response (200) - **id** (object) - An object where keys are theme IDs and values contain theme details. - **name** (string) - The display name of the theme. - **isDark** (boolean) - Indicates if the theme is dark. #### Response Example ```json { "ambiance": { "name": "Ambiance", "isDark": true }, "chaos": { "name": "Chaos", "isDark": true }, "chrome": { "name": "Chrome", "isDark": false } } ``` ``` -------------------------------- ### Checkbox Input Widget Configuration Source: https://docs.posit.co/ide/user/ide/guide/productivity/project-templates Configures a checkbox input for a project template parameter. 'Parameter' links the widget to a function argument, 'Widget' specifies the input type, 'Label' provides user-facing text, 'Default' sets the initial state, and 'Position' controls its placement. ```text Parameter: check Widget: CheckboxInput Label: Checkbox Input Default: On Position: left__ ``` -------------------------------- ### General Insertion Shortcut Source: https://docs.posit.co/ide/user/ide/guide/documents/visual-editor Details the universal shortcut for inserting various elements into the Quarto editor by typing the desired content after invoking the shortcut. ```General Cmd+/ / Ctrl+/ ``` -------------------------------- ### Save project state with renv Source: https://docs.posit.co/ide/user/ide/guide/environments/r/renv Saves the current state of the project's package library to the renv.lock file. This is a crucial step for reproducibility. ```r renv::snapshot() ``` -------------------------------- ### Back and Forward Navigation Shortcuts in RStudio Source: https://docs.posit.co/ide/user/ide/guide/code/code-navigation Traverse through recent navigation actions like opening files, going to definitions, or jumping to lines. ```RStudio Ctrl+F9 (Back) Cmd+F9 (Mac) Ctrl+F10 (Forward) Cmd+F10 (Mac) ```