### Access Example Google Sheets Source: https://context7.com/tidyverse/googlesheets4/llms.txt The `gs4_example` and `gs4_examples` functions provide access to built-in example sheets for testing and demonstration purposes. `gs4_examples` lists available examples, while `gs4_example` retrieves a specific sheet. ```r library(googlesheets4) # List all available examples gs4_examples() # Filter examples by pattern gs4_examples("gap") # Get specific example by name ss <- gs4_example("gapminder") read_sheet(ss) ss <- gs4_example("deaths") read_sheet(ss, range = "A1:F10") # View example in browser gs4_browse(gs4_example("mini-gap")) ``` -------------------------------- ### Access Example Sheets Source: https://context7.com/tidyverse/googlesheets4/llms.txt Shows how to access and use built-in example sheets for testing and demonstration. ```APIDOC ## gs4_example / gs4_examples - Access example Sheets ### Description Access built-in example sheets provided by the googlesheets4 package for testing and documentation. ### Method `gs4_example()` and `gs4_examples()` ### Parameters #### Path Parameters None #### Query Parameters - **pattern** (character) - A pattern to filter example sheet names. #### Request Body - **name** (character) - The name of the specific example sheet to access (for `gs4_example`). ### Request Example ```r # List all available examples gs4_examples() # Filter examples by pattern gs4_examples("gap") # Get specific example by name ss <- gs4_example("gapminder") read_sheet(ss) ss <- gs4_example("deaths") read_sheet(ss, range = "A1:F10") # View example in browser gs4_browse(gs4_example("mini-gap")) ``` ### Response #### Success Response (200) - **gs4_examples**: A character vector of available example sheet names. - **gs4_example**: A googlesheets4 object representing the specified example sheet. #### Response Example (No specific example provided, returns character vectors or googlesheets4 objects) ``` -------------------------------- ### Install googlesheets4 Package Source: https://github.com/tidyverse/googlesheets4/blob/main/README.md Install the released version of the googlesheets4 package from CRAN. ```r install.packages("googlesheets4") ``` -------------------------------- ### Install Development Version of googlesheets4 Source: https://github.com/tidyverse/googlesheets4/blob/main/README.md Install the development version of the googlesheets4 package from GitHub using the pak package. ```r #install.packages("pak") pak::pak("tidyverse/googlesheets4") ``` -------------------------------- ### Reject unrecognized properties in new() Source: https://github.com/tidyverse/googlesheets4/blob/main/tests/testthat/_snaps/schemas.md These examples demonstrate how the new() constructor rejects unexpected properties when creating a Spreadsheet object. ```R new("Spreadsheet", foofy = "blah") ``` ```R new("Spreadsheet", foofy = "blah", foo = "bar") ``` -------------------------------- ### Handle missing schema in check_against_schema() Source: https://github.com/tidyverse/googlesheets4/blob/main/tests/testthat/_snaps/schemas.md This example shows the error triggered when check_against_schema() cannot locate a valid schema for the provided object. ```R check_against_schema(x) ``` -------------------------------- ### Get Sheet Metadata Source: https://context7.com/tidyverse/googlesheets4/llms.txt Details how to retrieve comprehensive metadata about a Google Sheet. ```APIDOC ## gs4_get - Get Sheet metadata ### Description Retrieves detailed metadata about a spreadsheet including worksheets, named ranges, and properties. ### Method `gs4_get()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **ss** (googlesheets4 object or character) - The spreadsheet to retrieve metadata for. ### Request Example ```r ss <- gs4_example("deaths") # Get full metadata meta <- gs4_get(ss) ``` ### Response #### Success Response (200) A list containing spreadsheet metadata, including: - **spreadsheet_id**: The unique ID of the spreadsheet. - **name**: The name of the spreadsheet. - **sheets**: A tibble of worksheet information. - **named_ranges**: A tibble of named ranges. #### Response Example ``` # meta$spreadsheet_id # meta$name # meta$sheets # meta$named_ranges ``` ``` -------------------------------- ### Get info on current user Source: https://context7.com/tidyverse/googlesheets4/llms.txt Retrieves information about the currently authenticated Google user. ```r library(googlesheets4) # Check who is currently authenticated gs4_user() #> Logged in to googlesheets4 as jenny@example.com. ``` -------------------------------- ### Get Worksheet Metadata Source: https://context7.com/tidyverse/googlesheets4/llms.txt Explains how to retrieve information about worksheets, including their properties and names. ```APIDOC ## sheet_properties / sheet_names - Get worksheet metadata ### Description Retrieves information about worksheets in a spreadsheet. ### Method `sheet_properties()` and `sheet_names()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **ss** (googlesheets4 object) - The spreadsheet to retrieve information from. ### Request Example ```r ss <- gs4_example("gapminder") # Get detailed properties as tibble props <- sheet_properties(ss) # Get just the names names <- sheet_names(ss) ``` ### Response #### Success Response (200) - **sheet_properties**: A tibble with columns: name, index, id, type, visible, grid_rows, grid_columns. - **sheet_names**: A character vector of worksheet names. #### Response Example ``` # props tibble example: # A tibble with columns: name, index, id, type, visible, grid_rows, grid_columns # names vector example: # [1] "Africa" "Americas" "Asia" "Europe" "Oceania" ``` ``` -------------------------------- ### Open a Google Sheet in the Browser Source: https://context7.com/tidyverse/googlesheets4/llms.txt Use `gs4_browse` to open a specified Google Sheet directly in your default web browser. This can be done using an example sheet, a sheet ID, or a sheet object. ```r library(googlesheets4) # Open example sheet gs4_example("deaths") %>% gs4_browse() # Open by ID gs4_browse("1U6Cf_qEOhiR9AZqTqS3mbMF3zt2db48ZP5v3rkrAEJY") # Open after creating ss <- gs4_create("my-new-sheet", sheets = head(mtcars)) gs4_browse(ss) ``` -------------------------------- ### Validate col_names type and length Source: https://github.com/tidyverse/googlesheets4/blob/main/tests/testthat/_snaps/range_read.md These examples demonstrate errors when col_names is provided with incorrect data types or empty character vectors. ```R wrapper_fun(1:3) ``` ```R wrapper_fun(factor("a")) ``` ```R wrapper_fun(character()) ``` -------------------------------- ### Validate logical col_names values Source: https://github.com/tidyverse/googlesheets4/blob/main/tests/testthat/_snaps/range_read.md These examples demonstrate errors when col_names is provided with invalid logical values such as NA or vectors of length greater than one. ```R wrapper_fun(NA) ``` ```R wrapper_fun(c(TRUE, FALSE)) ``` -------------------------------- ### Append rows to a sheet Source: https://context7.com/tidyverse/googlesheets4/llms.txt Demonstrates how to append new rows to the end of an existing worksheet in a Google Sheet without overwriting existing data. Includes examples for appending single and multiple rows. ```r library(googlesheets4) # Create sheet with initial data initial_data <- data.frame( name = c("Alice", "Bob"), score = c(85, 92) ) ss <- gs4_create("scores", sheets = list(results = initial_data)) ``` ```r # Append single row new_row <- data.frame(name = "Carol", score = 88) sheet_append(ss, new_row, sheet = "results") ``` ```r # Append multiple rows more_rows <- data.frame( name = c("Dave", "Eve"), score = c(95, 78) ) sheet_append(ss, more_rows, sheet = "results") ``` ```r # Verify data read_sheet(ss, sheet = "results") #> name score #> 1 Alice 85 #> 2 Bob 92 #> 3 Carol 88 #> 4 Dave 95 #> 5 Eve 78 ``` -------------------------------- ### Get Google Sheet Metadata Source: https://context7.com/tidyverse/googlesheets4/llms.txt The `gs4_get` function retrieves comprehensive metadata for a Google Sheet, including its ID, name, locale, timezone, and details about its worksheets and named ranges. ```r library(googlesheets4) ss <- gs4_example("deaths") # Get full metadata meta <- gs4_get(ss) # Access specific properties meta$spreadsheet_id meta$name meta$sheets # tibble of worksheet info meta$named_ranges # tibble of named ranges ``` -------------------------------- ### Get Worksheet Metadata Source: https://context7.com/tidyverse/googlesheets4/llms.txt Use `sheet_properties` to retrieve detailed metadata about worksheets, including name, index, ID, type, visibility, and grid dimensions. `sheet_names` returns only the worksheet names. ```r library(googlesheets4) ss <- gs4_example("gapminder") # Get detailed properties as tibble props <- sheet_properties(ss) ``` ```r # Get just the names names <- sheet_names(ss) ``` -------------------------------- ### Configure authentication with client or path Source: https://github.com/tidyverse/googlesheets4/blob/main/tests/testthat/_snaps/gs4_auth.md Provide either a client object or a path to a JSON file, but not both simultaneously. ```R gs4_auth_configure(client = gargle::gargle_client(), path = "PATH") ``` -------------------------------- ### Create a new Sheet Source: https://context7.com/tidyverse/googlesheets4/llms.txt Initializes a new Google Sheet with optional data and configuration. ```r library(googlesheets4) # Create empty sheet with random name ss <- gs4_create() # Create with specific name ss <- gs4_create("my-analysis-results") ``` -------------------------------- ### Configure authentication with deprecated app argument Source: https://github.com/tidyverse/googlesheets4/blob/main/tests/testthat/_snaps/gs4_auth.md The app argument is deprecated; use the client argument instead. ```R gs4_auth_configure(app = client) ``` -------------------------------- ### Create a new Google Sheet Source: https://context7.com/tidyverse/googlesheets4/llms.txt Demonstrates various ways to create a new Google Sheet, including specifying locale, timezone, named empty sheets, initial data, or multiple named data frames. ```r ss <- gs4_create( "french-report", locale = "fr_FR", timeZone = "Europe/Paris" ) ``` ```r ss <- gs4_create( "quarterly-report", sheets = c("Q1", "Q2", "Q3", "Q4") ) ``` ```r my_data <- data.frame(x = 1:5, y = letters[1:5]) ss <- gs4_create("my-data-sheet", sheets = my_data) ``` ```r ss <- gs4_create( "multi-sheet-workbook", sheets = list( chickwts = head(chickwts), mtcars = head(mtcars), iris = head(iris) ) ) ``` -------------------------------- ### Load package for development Source: https://github.com/tidyverse/googlesheets4/blob/main/data-raw/errors/404-nonexistent-sheet.md Loads the current package for testing and development purposes. ```r devtools::load_all(".") ``` -------------------------------- ### Create a New Google Sheet with Initial Data Source: https://github.com/tidyverse/googlesheets4/blob/main/README.md Creates a new Google Sheet named 'fluffy-bunny' and writes the head of the 'iris' dataset to a sheet named 'flowers'. ```r (ss <- gs4_create("fluffy-bunny", sheets = list(flowers = head(iris)))) ``` -------------------------------- ### Open Sheet in Browser Source: https://context7.com/tidyverse/googlesheets4/llms.txt Demonstrates how to open a Google Sheet directly in the default web browser. ```APIDOC ## gs4_browse - Open Sheet in browser ### Description Opens a Google Sheet in your default web browser. ### Method `gs4_browse()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **ss** (googlesheets4 object or character) - The spreadsheet to open, can be a googlesheets4 object or its ID. ### Request Example ```r # Open example sheet gs4_example("deaths") %>% gs4_browse() # Open by ID gs4_browse("1U6Cf_qEOhiR9AZqTqS3mbMF3zt2db48ZP5v3rkrAEJY") # Open after creating ss <- gs4_create("my-new-sheet", sheets = head(mtcars)) gs4_browse(ss) ``` ### Response #### Success Response (200) Opens the specified Google Sheet in the default web browser. No direct return value is typically captured in R. #### Response Example (Opens a browser tab, no R output) ``` -------------------------------- ### Attach googlesheets4 Package Source: https://github.com/tidyverse/googlesheets4/blob/main/README.md Load the googlesheets4 package into the R session to use its functions. ```r library(googlesheets4) ``` -------------------------------- ### Write data to a Sheet Source: https://context7.com/tidyverse/googlesheets4/llms.txt Shows how to write data frames to Google Sheets, either creating a new sheet with a random name or writing to specific existing sheets and worksheets, with options to overwrite or create new ones. ```r library(googlesheets4) # Write data frame, creating a new Sheet with random name df <- data.frame(x = 1:3, y = letters[1:3]) ss <- write_sheet(df) ``` ```r ss <- gs4_create("write-demo", sheets = list(placeholder = data.frame(x = 1))) sheet_write(df, ss = ss) # Creates sheet named "df" from variable name ``` ```r sheet_write(mtcars, ss = ss, sheet = "mtcars_data") ``` ```r sheet_write(iris, ss = ss, sheet = "mtcars_data") ``` ```r gs4_browse(ss) ``` ```r sheet_properties(ss) ``` -------------------------------- ### Specify Cell Ranges Source: https://context7.com/tidyverse/googlesheets4/llms.txt Explains the use of helper functions for programmatically specifying cell ranges. ```APIDOC ## cell_rows / cell_cols / cell_limits - Specify cell ranges ### Description Helper functions from the cellranger package for specifying cell ranges programmatically. Useful when bounds are determined by data rather than hardcoded. ### Method `cell_rows()`, `cell_cols()`, `cell_limits()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **cell_rows**: A vector of row numbers. - **cell_cols**: A vector of column numbers. - **cell_limits**: A list containing `rows` and `cols` arguments. ### Request Example ```r library(googlesheets4) ss <- gs4_example("mini-gap") # Read specific rows only read_sheet(ss, range = cell_rows(1:3)) ``` ### Response #### Success Response (200) Returns objects that can be used to define cell ranges for googlesheets4 functions. #### Response Example (Returns range specification objects, not directly visible R output) ``` -------------------------------- ### Add worksheets to a spreadsheet Source: https://context7.com/tidyverse/googlesheets4/llms.txt Demonstrates how to add one or more new worksheets to an existing Google Sheet using the `sheet_add` function. ```r library(googlesheets4) # Create base spreadsheet ss <- gs4_create("sheet-management-demo") # Add single sheet with auto-generated name sheet_add(ss) ``` -------------------------------- ### Handle nonexistent sheets_id Source: https://github.com/tidyverse/googlesheets4/blob/main/tests/testthat/_snaps/sheets_id-class.md Demonstrates that the print method handles nonexistent IDs gracefully by reporting a 404 error. ```R as_sheets_id("12345") ``` -------------------------------- ### Display Spreadsheet Object After Writing Source: https://github.com/tidyverse/googlesheets4/blob/main/README.md Displays the 'ss' spreadsheet object after data has been written to it, showing the updated sheet structure. ```r ss ``` -------------------------------- ### Create and write Google Sheets formulas Source: https://context7.com/tidyverse/googlesheets4/llms.txt Use gs4_formula to mark strings as formulas so they are interpreted as such in Google Sheets rather than as plain text. ```r library(googlesheets4) # Create data with numeric values dat <- data.frame(x = c(1, 5, 3, 2, 4, 6)) ss <- gs4_create("formula-demo", sheets = dat) # Create summary with formulas summaries <- tibble::tibble( desc = c("max", "sum", "min", "average"), formula = gs4_formula(c( "=MAX(A:A)", "=SUM(A:A)", "=MIN(A:A)", "=AVERAGE(A:A)" )) ) # Write formulas to sheet range_write(ss, data = summaries, range = "C1", reformat = FALSE) # Formulas with special functions special <- tibble::tibble( desc = c("hyperlink", "image", "sparkline"), example = gs4_formula(c( '=HYPERLINK("http://www.google.com/","Google")', '=IMAGE("https://www.google.com/images/srpr/logo3w.png")', '=SPARKLINE(A:A, {"color", "blue"})' )) ) sheet_write(special, ss = ss, sheet = "special") # Clean up googledrive::drive_trash(ss) ``` -------------------------------- ### Creating and Writing Sheets Source: https://context7.com/tidyverse/googlesheets4/llms.txt Functions for creating new Google Sheets. ```APIDOC ## gs4_create - Create a new Sheet ### Description Creates a new Google Sheet with optional initial data and worksheet configuration. ### Method Not applicable (R function) ### Endpoint Not applicable (R function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```r library(googlesheets4) # Create empty sheet with random name ss <- gs4_create() # Create with specific name ss <- gs4_create("my-analysis-results") ``` ### Response #### Success Response (200) A googlesheets4 spreadsheet object representing the newly created sheet. #### Response Example ```r # Example spreadsheet object # # Local path: /tmp/Rtmp.../my-analysis-results.csv # Remote path: https://docs.google.com/spreadsheets/d/1ABCdefGHIjklMNOpqrSTuvWXYZ1234567890/edit # Title: my-analysis-results # Sheets: Sheet1 ``` ``` -------------------------------- ### Add Named Sheets Source: https://context7.com/tidyverse/googlesheets4/llms.txt Demonstrates how to add new worksheets to a Google Sheet with specified names and positions. ```APIDOC ## sheet_add ### Description Adds one or more worksheets to a spreadsheet. ### Method `sheet_add()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **ss** (googlesheets4 object) - The spreadsheet to add sheets to. - **sheet** (character or list) - The name(s) of the sheet(s) to add. - **.before** (integer or character) - Position or name of the sheet to insert before. - **.after** (integer or character) - Position or name of the sheet to insert after. - **gridProperties** (list) - List of properties for the new sheet (e.g., rowCount, columnCount, frozenRowCount). ### Request Example ```r # Add named sheets sheet_add(ss, "Sales") sheet_add(ss, "Inventory", .after = 1) sheet_add(ss, "Summary", .before = "Sales") # Add multiple sheets at once sheet_add(ss, c("Q1", "Q2", "Q3", "Q4")) # Add sheet with specific properties sheet_add( ss, sheet = "Custom", .before = 1, gridProperties = list(rowCount = 50, columnCount = 10, frozenRowCount = 1) ) ``` ### Response #### Success Response (200) Returns the modified spreadsheet object. #### Response Example (No specific example provided, returns spreadsheet object) ``` -------------------------------- ### gs4_create Source: https://context7.com/tidyverse/googlesheets4/llms.txt Creates a new Google Sheet with optional locale, timezone, and initial sheets or data. ```APIDOC ## gs4_create ### Description Creates a new Google Sheet. Can be initialized with specific locale, timezone, or pre-populated with named empty sheets or data frames. ### Parameters - **name** (string) - Required - The name of the new spreadsheet. - **locale** (string) - Optional - The locale for the spreadsheet (e.g., "fr_FR"). - **timeZone** (string) - Optional - The timezone for the spreadsheet (e.g., "Europe/Paris"). - **sheets** (vector/list) - Optional - Initial sheets to create, can be names or data frames. ``` -------------------------------- ### Generate and execute a spreadsheet request Source: https://github.com/tidyverse/googlesheets4/blob/main/data-raw/errors/404-nonexistent-sheet.md Generates a request for a specific spreadsheet ID and processes the response, which triggers an error if the sheet does not exist. ```r req <- request_generate( "spreadsheets.get", ## ID of 'googlesheets4-design-exploration', but replaced last 2 chars w/ '-' list(spreadsheetId = "1xTUxWGcFLtDIHoYJ1WsjQuLmpUtBf--8Bcu5lQ302--"), token = NULL ) raw_resp <- request_make(req) response_process(raw_resp) ``` -------------------------------- ### Generate test data with gs4_fodder Source: https://context7.com/tidyverse/googlesheets4/llms.txt Creates a data frame with cell values reflecting their coordinates, useful for testing. ```r library(googlesheets4) # Default 10x10 grid df <- gs4_fodder() #> A B C ... #> 1 B2 C2 D2 ... #> 2 B3 C3 D3 ... #> ... # Custom size df <- gs4_fodder(5, 3) # 5 rows, 3 columns #> A B C #> 1 B2 C2 D2 #> 2 B3 C3 D3 #> 3 B4 C4 D4 #> 4 B5 C5 D5 #> 5 B6 C6 D6 ``` -------------------------------- ### Fast CSV-based reading Source: https://context7.com/tidyverse/googlesheets4/llms.txt Provides a faster alternative to read_sheet() by parsing CSV exports, suitable for large spreadsheets. ```r library(googlesheets4) # Fast read with readr column type specification if (require("readr")) { data <- range_speedread( gs4_example("deaths"), sheet = "other", range = "A5:F15", col_types = cols( Age = col_integer(), `Date of birth` = col_date("%m/%d/%Y"), `Date of death` = col_date("%m/%d/%Y") ) ) } # Simple speed read data <- range_speedread(gs4_example("mini-gap")) ``` -------------------------------- ### Find Google Sheets Source: https://context7.com/tidyverse/googlesheets4/llms.txt Explains how to search for Google Sheets within your Google Drive. ```APIDOC ## gs4_find - Find Google Sheets ### Description Searches for Google Sheets in your Drive. Thin wrapper around googledrive::drive_find(). ### Method `gs4_find()` ### Parameters #### Path Parameters None #### Query Parameters - **pattern** (character) - A pattern to search for in sheet names. - **q** (character) - A query string for more advanced filtering (e.g., folder location). - **order_by** (character) - Field to sort results by (e.g., 'createdTime desc'). - **n_max** (integer) - Maximum number of results to return. ### Request Example ```r # List all your sheets all_sheets <- gs4_find() # Find sheets by name pattern my_reports <- gs4_find(pattern = "report") # Limit results, sorted by creation time recent <- gs4_find(order_by = "createdTime desc", n_max = 5) # Search in specific folder folder_sheets <- gs4_find( q = "'folder-id-here' in parents" ) ``` ### Response #### Success Response (200) A data frame of found Google Sheets, with columns like name, id, and webViewLink. #### Response Example (No specific example provided, returns a data frame) ``` -------------------------------- ### Move Worksheets Source: https://context7.com/tidyverse/googlesheets4/llms.txt Provides instructions on how to reorder worksheets within a spreadsheet. ```APIDOC ## sheet_relocate - Move worksheets ### Description Reorders worksheets within a spreadsheet. ### Method `sheet_relocate()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **ss** (googlesheets4 object) - The spreadsheet containing the sheets to reorder. - **sheet** (integer, character, or list) - The position(s) or name(s) of the sheet(s) to move. - **.before** (integer or character) - Position or name of the sheet to move before. - **.after** (integer or character) - Position or name of the sheet to move after. ### Request Example ```r # Create sheet with multiple worksheets sheet_names_list <- c("alfa", "bravo", "charlie", "delta", "echo", "foxtrot") ss <- gs4_create("relocate-demo", sheets = sheet_names_list) # Move sheet before another sheet_relocate(ss, "echo", .before = "bravo") # Move sheet after another sheet_relocate(ss, "echo", .after = "delta") # Move multiple sheets to front (reorder) sheet_relocate(ss, list("foxtrot", 4)) # Move multiple sheets to back sheet_relocate(ss, c("bravo", "alfa", "echo"), .after = 100) # Restore original order sheet_relocate(ss, sheet_names_list) ``` ### Response #### Success Response (200) Returns the modified spreadsheet object. #### Response Example (No specific example provided, returns spreadsheet object) ``` -------------------------------- ### Fill or clear cell ranges Source: https://context7.com/tidyverse/googlesheets4/llms.txt Demonstrates how to fill a range of cells with a single value or clear cell values and formatting using `range_flood` and `range_clear`. ```r library(googlesheets4) # Create sheet with sample data df <- gs4_fodder(10) # 10x10 grid of cell references ss <- gs4_create("flood-demo", sheets = list(data = df)) ``` ```r # Clear cell values and formatting range_flood(ss, range = "A1:B3") ``` ```r # Clear value but keep formatting range_flood(ss, range = "C1:D3", reformat = FALSE) ``` ```r # Fill range with value range_flood(ss, range = "4:5", cell = "FILLED") ``` ```r # range_clear is a shortcut for clearing range_clear(ss, range = "9:9") range_clear(ss, range = "10:10", reformat = FALSE) ``` -------------------------------- ### Generate random sheet names Source: https://context7.com/tidyverse/googlesheets4/llms.txt Creates random names using adjective-animal combinations for new sheets. ```r library(googlesheets4) # Generate a random name gs4_random() #> [1] "happy-panda" # Generate multiple names gs4_random(5) #> [1] "calm-tiger" "swift-eagle" "bold-otter" "warm-koala" "quick-fox" ``` -------------------------------- ### List Google Sheets API scopes Source: https://github.com/tidyverse/googlesheets4/blob/main/tests/testthat/_snaps/gs4_auth.md Returns a named vector of available Google Sheets and Drive API scopes. ```R gs4_scopes() ``` -------------------------------- ### Inspect error content Source: https://github.com/tidyverse/googlesheets4/blob/main/data-raw/errors/404-nonexistent-sheet.md Extracts and displays the content of the HTTP response to inspect the error details. ```r ct <- httr::content(raw_resp) str(ct) ``` -------------------------------- ### Authentication Functions Source: https://context7.com/tidyverse/googlesheets4/llms.txt Functions for authorizing and managing authentication with Google Sheets. ```APIDOC ## gs4_auth - Authorize googlesheets4 ### Description Authorizes googlesheets4 to interact with Google Sheets on behalf of the user. This function handles OAuth 2.0 authentication flow, supporting various methods including browser-based auth, service account tokens, and cached credentials. ### Method Not applicable (R function) ### Endpoint Not applicable (R function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```r library(googlesheets4) # Basic auth - opens browser for interactive auth gs4_auth() # Auth with specific email gs4_auth(email = "jenny@example.com") # Force new browser auth, ignoring cached credentials gs4_auth(email = NA) # Use read-only scope (can't edit or delete sheets) gs4_auth(scopes = "spreadsheets.readonly") # Use service account token gs4_auth(path = "path/to/service-account-key.json") # Share auth token with googledrive package goodledrive::drive_auth(token = gs4_token()) ``` ### Response #### Success Response (200) Authentication token or user information. #### Response Example ```r # Example output (not a direct return value, but indicates success) # Logged in to googlesheets4 as jenny@example.com. ``` ``` ```APIDOC ## gs4_deauth - Suspend authorization ### Description Puts googlesheets4 into a deauthorized state, using only an API key for public sheets. Useful for accessing world-readable sheets without authentication. ### Method Not applicable (R function) ### Endpoint Not applicable (R function) ### Parameters None ### Request Example ```r library(googlesheets4) # Go into deauthorized state gs4_deauth() # Check current user (will show not logged in) gs4_user() # Can still read public sheets public_sheet <- gs4_example("gapminder") data <- read_sheet(public_sheet) ``` ### Response #### Success Response (200) No direct return value, but changes the authentication state. #### Response Example None ``` ```APIDOC ## gs4_user - Get info on current user ### Description Returns information about the currently authenticated Google user. ### Method Not applicable (R function) ### Endpoint Not applicable (R function) ### Parameters None ### Request Example ```r library(googlesheets4) # Check who is currently authenticated gs4_user() ``` ### Response #### Success Response (200) Information about the authenticated Google user. #### Response Example ```r #> Logged in to googlesheets4 as jenny@example.com. ``` ``` -------------------------------- ### Retrieve deprecated OAuth app Source: https://github.com/tidyverse/googlesheets4/blob/main/tests/testthat/_snaps/gs4_auth.md This function is deprecated as of version 1.1.0; use gs4_oauth_client() instead. ```R absorb <- gs4_oauth_app() ``` -------------------------------- ### sheet_add Source: https://context7.com/tidyverse/googlesheets4/llms.txt Adds one or more new worksheets to an existing spreadsheet. ```APIDOC ## sheet_add ### Description Adds new worksheets to an existing spreadsheet. ### Parameters - **ss** (string/object) - Required - The spreadsheet. ``` -------------------------------- ### Specify Cell Ranges Programmatically Source: https://context7.com/tidyverse/googlesheets4/llms.txt Helper functions `cell_rows`, `cell_cols`, and `cell_limits` from the `cellranger` package allow programmatic specification of cell ranges. This is useful when ranges are determined dynamically. ```r library(googlesheets4) ss <- gs4_example("mini-gap") # Read specific rows only read_sheet(ss, range = cell_rows(1:3)) ``` -------------------------------- ### Read Sheet from URL Source: https://github.com/tidyverse/googlesheets4/blob/main/README.md Read data from a Google Sheet using its URL. This function is a synonym for range_read(). ```r # URL read_sheet("https://docs.google.com/spreadsheets/d/1U6Cf_qEOhiR9AZqTqS3mbMF3zt2db48ZP5v3rkrAEJY/edit#gid=780868077") #> ✔ Reading from "gapminder". #> ✔ Range 'Africa'. #> # A tibble: 624 × 6 #> country continent year lifeExp pop gdpPercap #> #> 1 Algeria Africa 1952 43.1 9279525 2449. #> 2 Algeria Africa 1957 45.7 10270856 3014. #> 3 Algeria Africa 1962 48.3 11000948 2551. #> 4 Algeria Africa 1967 51.4 12760499 3247. #> 5 Algeria Africa 1972 54.5 14760787 4183. #> # ℹ 619 more rows ``` -------------------------------- ### sheet_write / write_sheet Source: https://context7.com/tidyverse/googlesheets4/llms.txt Writes a data frame into a worksheet, styling it as a table with a frozen header row. ```APIDOC ## sheet_write / write_sheet ### Description Writes a data frame into a worksheet. It creates a new sheet or overwrites an existing one, applying table formatting. ### Parameters - **data** (data.frame) - Required - The data to write. - **ss** (string/object) - Required - The spreadsheet to write to. - **sheet** (string) - Optional - The name of the worksheet to write to. ``` -------------------------------- ### Read a Google Sheet Source: https://github.com/tidyverse/googlesheets4/blob/main/README.md Reads a Google Sheet named 'gapminder' into an R tibble. Requires the account to have a Sheet with that name. ```r googledrive::drive_get("gapminder") %>% read_sheet() ``` -------------------------------- ### Read specific columns and rows in Google Sheets Source: https://context7.com/tidyverse/googlesheets4/llms.txt Use cell_cols and cell_rows to define specific ranges for reading data from a sheet. ```r read_sheet(ss, range = cell_cols("C:D")) read_sheet(ss, range = cell_cols(1)) ``` ```r read_sheet(ss, range = cell_rows(c(NA, 4))) # rows 1-4 read_sheet(ss, range = cell_rows(c(3, NA))) # rows 3 to end read_sheet(ss, range = cell_cols(c(NA, "D"))) # columns A-D read_sheet(ss, range = cell_cols(c(2, NA))) # column B to end ``` ```r read_sheet(ss, range = cell_limits(c(2, 3), c(NA, NA)), col_names = FALSE) read_sheet(ss, range = cell_limits(c(1, 2), c(NA, 4))) ``` -------------------------------- ### Write data to a specific range Source: https://context7.com/tidyverse/googlesheets4/llms.txt Explains how to write data to a specific cell range within a Google Sheet without applying table formatting. Useful for precise data placement. ```r library(googlesheets4) # Create sheet with empty worksheets ss <- gs4_create("range-write-demo", sheets = c("data", "summary")) ``` ```r # Write data starting at specific cell df <- data.frame(x = 1:3, y = letters[1:3]) range_write(ss, data = df, range = "D6") ``` ```r # Write to specific sheet range_write(ss, data = df, sheet = "summary", range = "A1") ``` ```r # Write without column names (useful for arbitrary data) dat <- tibble::tibble( string = "string", logical = TRUE, datetime = Sys.time() ) range_write(ss, data = dat, sheet = "data", range = "A10", col_names = FALSE) ``` ```r # Write column of data column_data <- tibble::tibble(x = list(Sys.time(), FALSE, "string")) range_write(ss, data = column_data, range = "F5", col_names = FALSE) ``` ```r # Write without reformatting (preserve existing cell formats) range_write(ss, data = df, range = "H1", reformat = FALSE) ``` -------------------------------- ### Authorize googlesheets4 Source: https://context7.com/tidyverse/googlesheets4/llms.txt Handles OAuth 2.0 authentication flow for interacting with private Google Sheets. ```r library(googlesheets4) # Basic auth - opens browser for interactive auth gs4_auth() # Auth with specific email gs4_auth(email = "jenny@example.com") # Force new browser auth, ignoring cached credentials gs4_auth(email = NA) # Use read-only scope (can't edit or delete sheets) gs4_auth(scopes = "spreadsheets.readonly") # Use service account token gs4_auth(path = "path/to/service-account-key.json") # Share auth token with googledrive package googledrive::drive_auth(token = gs4_token()) ``` -------------------------------- ### Read raw cell data Source: https://context7.com/tidyverse/googlesheets4/llms.txt Retrieves low-level cell data including formulas and metadata. ```r library(googlesheets4) # Get raw cell data ss <- gs4_example("mini-gap") cells <- range_read_cells(ss) #> Returns data frame with row, col, and cell list-column # Convert to spreadsheet shape df <- spread_sheet(cells) ``` -------------------------------- ### Reading Data Source: https://context7.com/tidyverse/googlesheets4/llms.txt Functions for reading data from Google Sheets into R. ```APIDOC ## read_sheet / range_read - Read a Sheet into a data frame ### Description The main "read" function that reads data from a Google Sheet into an R tibble. Supports reading by URL, Sheet ID, or googledrive dribble object. ### Method Not applicable (R function) ### Endpoint Not applicable (R function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```r library(googlesheets4) # Read from URL data <- read_sheet("https://docs.google.com/spreadsheets/d/1U6Cf_qEOhiR9AZqTqS3mbMF3zt2db48ZP5v3rkrAEJY/edit#gid=780868077") # Read from Sheet ID data <- read_sheet("1U6Cf_qEOhiR9AZqTqS3mbMF3zt2db48ZP5v3rkrAEJY") # Read specific sheet and range ss <- gs4_example("deaths") data <- read_sheet(ss, sheet = "other", range = "A5:F15") # Specify column types using readr-style shortcodes # c=character, i=integer, l=logical, D=Date, d/n=numeric, ?=guess data <- read_sheet(ss, range = "other!A5:F15", col_types = "ccilDD") # Read with named range data <- read_sheet(ss, range = "arts_data", col_types = "ccilDD") # Read from googledrive dribble library(googledrive) dribble <- drive_get("my-spreadsheet") data <- read_sheet(dribble) # Skip rows and limit results data <- read_sheet(ss, skip = 5, n_max = 10) # Custom column names data <- read_sheet(ss, col_names = c("Name", "Age", "City")) ``` ### Response #### Success Response (200) An R tibble containing the data from the specified Google Sheet. #### Response Example ```r # Example tibble structure # A tibble: 10 × 6 Name Age City `Date of birth` `Date of death` Formula 1 Alice 30 New York 1993-05-15 2023-01-20 =SUM(A1:A2) 2 Bob 25 London 1998-11-01 NA =AVERAGE(B1:B3) ... (rest of data) ``` ``` ```APIDOC ## range_speedread - Fast CSV-based reading ### Description A faster alternative to read_sheet() that bypasses the Sheets API and parses a CSV export. Best for large spreadsheets where speed is critical, but has limitations on cell type detection and range specification. ### Method Not applicable (R function) ### Endpoint Not applicable (R function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```r library(googlesheets4) # Fast read with readr column type specification if (require("readr")) { data <- range_speedread( gs4_example("deaths"), sheet = "other", range = "A5:F15", col_types = cols( Age = col_integer(), `Date of birth` = col_date("%m/%d/%Y"), `Date of death` = col_date("%m/%d/%Y") ) ) } # Simple speed read data <- range_speedread(gs4_example("mini-gap")) ``` ### Response #### Success Response (200) An R tibble containing the data from the specified Google Sheet, read via CSV export. #### Response Example ```r # Example tibble structure # A tibble: 10 × 6 Age `Date of birth` `Date of death` ... ... 1 30 1993-05-15 2023-01-20 ... 2 25 1998-11-01 NA ... ... (rest of data) ``` ``` ```APIDOC ## range_read_cells - Read raw cell data ### Description Returns low-level cell data including formulas, formats, and cell metadata. Useful when you need access to cell properties beyond just values. ### Method Not applicable (R function) ### Endpoint Not applicable (R function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```r library(googlesheets4) # Get raw cell data ss <- gs4_example("mini-gap") cells <- range_read_cells(ss) #> Returns data frame with row, col, and cell list-column # Convert to spreadsheet shape df <- spread_sheet(cells) ``` ### Response #### Success Response (200) A data frame with columns for row, col, and a list-column containing cell details. #### Response Example ```r # Example data frame structure # A tibble: 100 × 3 row col cell 1 1 1 2 1 2 ... (rest of cells) ``` ``` -------------------------------- ### Rename a Worksheet Source: https://context7.com/tidyverse/googlesheets4/llms.txt Details how to change the name of a worksheet within a Google Sheet. ```APIDOC ## sheet_rename - Rename a worksheet ### Description Changes the name of a worksheet. ### Method `sheet_rename()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **ss** (googlesheets4 object) - The spreadsheet containing the sheet to rename. - **sheet** (integer or character) - The current position or name of the sheet to rename. - **new_name** (character) - The new name for the worksheet. ### Request Example ```r # Create sheet with worksheets ss <- gs4_create( "rename-demo", sheets = list(cars = head(cars), chickwts = head(chickwts)) ) # Rename by position sheet_rename(ss, 1, new_name = "automobiles") # Rename by current name sheet_rename(ss, "chickwts", new_name = "poultry") ``` ### Response #### Success Response (200) Returns the modified spreadsheet object. #### Response Example (No specific example provided, returns spreadsheet object) ``` -------------------------------- ### Delete cells from a range Source: https://context7.com/tidyverse/googlesheets4/llms.txt Shows how to delete cells within a specified range in a Google Sheet, with options to shift remaining cells left or up to fill the gap. ```r library(googlesheets4) # Create sheet with sample data df <- gs4_fodder(10) ss <- gs4_create("delete-demo", sheets = list(data = df)) ``` ```r # Delete rows 2-4 (shifts remaining rows up) range_delete(ss, range = "2:4") ``` ```r # Delete column C (shifts remaining columns left) range_delete(ss, range = "C") ``` ```r # Delete rectangle with explicit shift direction range_delete(ss, range = "B3:F4", shift = "left") range_delete(ss, range = "B3:F4", shift = "up") ``` -------------------------------- ### Reorder Worksheets within a Google Sheet Source: https://context7.com/tidyverse/googlesheets4/llms.txt The `sheet_relocate` function allows reordering of worksheets. Sheets can be moved to specific positions using `.before` or `.after` arguments, or moved to the front/back. ```r library(googlesheets4) # Create sheet with multiple worksheets sheet_names_list <- c("alfa", "bravo", "charlie", "delta", "echo", "foxtrot") ss <- gs4_create("relocate-demo", sheets = sheet_names_list) # Move sheet before another sheet_relocate(ss, "echo", .before = "bravo") sheet_names(ss) # Move sheet after another sheet_relocate(ss, "echo", .after = "delta") # Move multiple sheets to front (reorder) sheet_relocate(ss, list("foxtrot", 4)) # Move multiple sheets to back sheet_relocate(ss, c("bravo", "alfa", "echo"), .after = 100) # Restore original order sheet_relocate(ss, sheet_names_list) # Clean up googledrive::drive_trash(ss) ``` -------------------------------- ### Suppress informational messages Source: https://context7.com/tidyverse/googlesheets4/llms.txt Use with_gs4_quiet or local_gs4_quiet to temporarily suppress console output from googlesheets4 functions. ```r library(googlesheets4) # Suppress messages for a single expression result <- with_gs4_quiet( read_sheet(gs4_example("mini-gap")) ) # Suppress messages in a local scope my_function <- function() { local_gs4_quiet() # All gs4 calls in this function will be quiet data <- read_sheet(gs4_example("deaths")) return(data) } ``` -------------------------------- ### Validate sheet_add() input type Source: https://github.com/tidyverse/googlesheets4/blob/main/tests/testthat/_snaps/sheet_add.md Demonstrates the error triggered when passing a numeric value to the sheet argument in sheet_add(). ```R sheet_add(test_sheet("googlesheets4-cell-tests"), sheet = 3) ``` -------------------------------- ### Print public sheets_id with deauth Source: https://github.com/tidyverse/googlesheets4/blob/main/tests/testthat/_snaps/sheets_id-class.md Displays metadata for a public sheet when the session is explicitly deauthorized. ```R print(gs4_example("mini-gap")) ``` -------------------------------- ### Find Google Sheets in Drive Source: https://context7.com/tidyverse/googlesheets4/llms.txt Use `gs4_find` to search for Google Sheets within your Google Drive. It supports searching by name pattern, ordering results, and limiting the number of returned sheets. ```r library(googlesheets4) # List all your sheets all_sheets <- gs4_find() # Find sheets by name pattern my_reports <- gs4_find(pattern = "report") # Limit results, sorted by creation time recent <- gs4_find(order_by = "createdTime desc", n_max = 5) # Search in specific folder folder_sheets <- gs4_find( q = "'folder-id-here' in parents" ) ``` -------------------------------- ### Validate Google Sheets ID format Source: https://github.com/tidyverse/googlesheets4/blob/main/tests/testthat/_snaps/sheets_id-class.md Ensures the provided string conforms to the required regular expression for a drive ID. ```R as_sheets_id("abc&123") ```