Package 'DataEditR'

Title: An Interactive Editor for Viewing, Entering, Filtering & Editing Data
Description: An interactive editor built on the 'Tabulator' JavaScript library to allow the interactive viewing, entering, filtering and editing of data in R, including tables stored in databases <https://dillonhammill.github.io/DataEditR/>.
Authors: Dillon Hammill [aut, cre] (ORCID: <https://orcid.org/0000-0002-1407-7223>), Oli Folkerd [ctb, cph] (Author of the included Tabulator library), Lucide Contributors [cph] (Icons based on Lucide)
Maintainer: Dillon Hammill <[email protected]>
License: GPL-2
Version: 2.0.0
Built: 2026-11-17 00:19:49 UTC
Source: https://github.com/dillonhammill/dataeditr

Help Index


Generate tidyverse code to replicate data edits

Description

data_code compares an original dataset with an edited version and generates tidyverse-style R code (using dplyr verbs) that transforms the original data into the edited version. The generated code uses rename(), select(), mutate(), slice(), and tibble::add_row() to replicate column renames, column additions/removals, cell value changes, and row additions/removals. When meaningful row names are present (i.e. non-default row names such as those in mtcars), the generated code preserves them using tibble::rownames_to_column() and tibble::column_to_rownames().

Usage

data_code(x, x_edit, name = "data")

Arguments

x

original data prior to editing, a data.frame or matrix. If NULL, creation code will be generated for x_edit.

x_edit

edited data after modifications, a data.frame or matrix.

name

character string for the name of the data object in the generated code, set to "data" by default.

Value

a character string containing tidyverse code that can be printed to the console or written to an R script.

Author(s)

Dillon Hammill, [email protected]

Examples

# original data
x <- data.frame(
  A = c(1, 2, 3),
  B = c("x", "y", "z"),
  stringsAsFactors = FALSE
)

# edited data (changed a value and renamed a column)
x_edit <- data.frame(
  A = c(1, 5, 3),
  Beta = c("x", "y", "z"),
  stringsAsFactors = FALSE
)

# generate code
cat(data_code(x, x_edit, name = "x"))

An interactive editor for viewing, entering and editing data

Description

data_edit is a shiny application built on the MIT-licensed 'Tabulator' JavaScript library that is designed to make it easy to interactively view, enter or edit data without any coding. data_edit is also a wrapper for any reading or writing function to make it easy to interactively update data saved to file, and can edit tables stored in a database.

Usage

data_edit(
  x = NULL,
  col_bind = NULL,
  col_edit = TRUE,
  col_options = NULL,
  col_stretch = FALSE,
  col_factor = FALSE,
  col_names = TRUE,
  col_readonly = NULL,
  col_hide = NULL,
  row_bind = NULL,
  row_edit = TRUE,
  save_as = NULL,
  title = NULL,
  logo = NULL,
  logo_size = 30,
  logo_side = "left",
  viewer = "dialog",
  viewer_height = 800,
  viewer_width = 1200,
  theme = NULL,
  read_fun = "read.csv",
  read_args = NULL,
  write_fun = "write.csv",
  write_args = NULL,
  quiet = FALSE,
  hide = FALSE,
  code = FALSE,
  cancel,
  track = TRUE,
  log = NULL,
  autosave = TRUE,
  col_actions = TRUE,
  rules = NULL,
  formats = NULL,
  col_summary = TRUE,
  row_names = TRUE,
  col_widths = NULL,
  page_rows = NULL,
  page_cols = NULL,
  ...
)

Arguments

x

a matrix, data.frame, data.table or the name of a csv file to edit. Tibbles are also supported. An empty table can be created by specifying the dimensions in a vector of the form c(nrow, ncol) or the names of the columns to include in the template. Database tables can be edited by supplying a dbplyr lazy table or a db_table().

col_bind

additional columns to add to the data prior to loading into editor, can be either an array containing the new data, a vector containing the new column names for empty columns or a named list containing a vector for each new column.

col_edit

logical indicating whether columns can be added or removed, set to TRUE by default.

col_options

a list named by column with the input to use for each column:

  • c(TRUE, FALSE) or "checkbox": checkboxes;

  • a vector of values, e.g. c("A", "B", "C"): a dropdown menu. Give the values names to show the names instead, as for shiny::selectInput(): list("New South Wales" = "NSW", "Victoria" = "VIC");

  • "dropdown": a dropdown menu of the values in the column (or the levels of a factor);

  • "date" or "datetime": a date or date-time picker (the column is returned as Date or POSIXct);

  • "time": a time picker ("HH:MM" text);

  • "textarea": text over several lines;

  • "password": hidden text;

  • "url": web addresses with a button to open them;

  • "html": cells shown as HTML (links, line breaks, bold, images, ...) without scripts or styles; double-click to edit the HTML;

  • "colour" (or "color"): colours (R colour names such as "grey50" or hex codes such as "#1D4ED8") shown with a swatch and edited with a colour picker. Set the colours the picker offers with list(type = "colour", palette = c("red", "#1D4ED8")); any colour can still be typed or picked;

  • c(min = 0, max = 10, step = 1) (any of the three): numbers within limits, in steps of step counted from min;

  • "integer": whole numbers, returned as integers (with limits: list(type = "integer", min = 0, max = 10));

  • "slider": a slider and bar for numbers from 0 to 100;

  • "rating": a rating from 0 to 5 stars.

Set the limits of a slider with c(type = "slider", min = 0, max = 1, step = 0.05) and the number of stars of a rating with c(type = "rating", stars = 10) (a list() works too). Values outside the limits or off the steps are marked in the editor and cannot be entered. Columns that are not in the data are ignored (with a message), here and in col_readonly, col_hide and col_widths, so the same settings can be used for different data.

col_stretch

logical indicating whether columns should be stretched to fill the full width of the display, set to FALSE by default.

col_factor

logical indicating whether character columns should be converted to factors prior to returning the edited data, set to FALSE by default. Factor columns in the data are always returned as factors with their levels; new values become new levels after the existing ones.

col_names

logical indicating whether column names can be edited or a vector of column names that cannot be edited, set to TRUE by default to allow editing of column names.

col_readonly

names of columns that cannot be edited. Values and names of these columns are locked in the grid.

col_hide

names of columns to hide from the editor. Hidden columns will not be visible or editable but will be retained in the returned data.

row_bind

additional rows to add to the data prior to loading into editor, can be either an array containing the new data, a vector containing the new row names for empty rows or a named list containing a vector for each new column.

row_edit

logical indicating whether rows can be added or removed, set to TRUE by default.

save_as

name of a csv file to which the edited data should be saved.

title

optional title to show in the header, set to the name of the data by default.

optional logo to include next to the title, supplied as the path or URL of an image. No logo is shown by default.

logo_size

width of the logo in pixels, set to 30 pixels by default.

logo_side

can be either "left" or "right" to determine the position of the logo relative to the title, set to "left" by default.

viewer

can be either "dialog", "browser" or "pane" to open the application in a dialog box, browser or RStudio viewer pane. First letter abbreviations are allowed, set to "dialog" by default. A function accepting the application URL can also be supplied. Outside RStudio the dialog opens in the browser. If code that runs after data_edit() inside a function of yours stops when the RStudio dialog closes, use viewer = "pane" or "browser" there.

viewer_height

numeric to control the height of the viewer in pixels when viewer is set to "dialog", set 800 by default.

viewer_width

numeric to control the width of the viewer in pixels when viewer is set to "dialog", set to 1200 by default.

theme

a Bootstrap 5 Bootswatch theme name (e.g. "yeti") or a bslib::bs_theme() object. Set to NULL by default to use the DataEditR theme.

read_fun

name of the function to use to read in the data when x is the name of a file, set to read.csv by default. SPSS (.sav, .por), Stata (.dta) and SAS (.sas7bdat, .xpt) files are read with the haven package unless another function is given (see the Labelled data section). Functions of other packages can be named with "pkg::fun", e.g. read_fun = "readxl::read_excel".

read_args

a named list of additional arguments to pass to read_fun.

write_fun

name of the function to use to write the edited version of x to a file, set to write.csv by default. Only requirement is that the first argument accepts the edited data and the second argument accepts the file name supplied to save_as. When save_as ends in .sav, .dta or .xpt the data is written with haven, keeping variable and value labels. Data without row names (only row numbers) is written by write.csv() without them, unless write_args sets row.names. "pkg::fun" names a function of another package, e.g. "googlesheets4::write_sheet", whose save_as need not be a file name.

write_args

a named list of additional arguments to pass to write_fun.

quiet

logical indicating whether messages should be suppressed, set to FALSE by default.

hide

logical indicating whether the Open and Export menus and the Done options should be hidden. When save_as is specified the edited data is written to file when Done is pressed.

code

logical indicating whether tidyverse code required to replicate the data edits should be printed to the console, set to FALSE by default. Alternatively, users can supply the name of an R script to write the code to. For data frames the generated code uses dplyr verbs such as rename(), select(), mutate(), slice(), and tibble::add_row(); for database tables it uses rows_update(), rows_append() and rows_delete().

cancel

optional value to return when the user hits the cancel button, set to the supplied data by default.

track

TRUE (the default) highlights cells that have been edited or added with a blue tint and border. Give a CSS colour (e.g. "#DC2626" or "red") to use another colour, or FALSE to turn the highlighting off.

log

name of a csv file to which the change log (who changed what and when, see dataEditLog()) is added when Done is pressed, with a first column data naming the data that was edited. The file is created if it does not exist, so the same file can keep the history of many editing sessions, and the History tab lists the earlier sessions of the same data kept in it. A function can be supplied instead; it is called with the log as a data frame (for example to write it to a database). Set to NULL by default to not keep the log.

autosave

logical indicating whether changes should be saved as a draft while editing, set to TRUE by default. If the editor is closed without pressing Done or Cancel (the window was closed, R crashed, ...), opening the same data again offers to restore the changes. See the Drafts section.

col_actions

logical indicating whether the column menu offers actions that change a whole column: formulas (e.g. a new column kpl = mpg * 0.425), find and replace, recoding values, changing the type and sorting the rows. Each action is shown in the generated code as one dplyr verb. Set to TRUE by default.

rules

a list of rules the data should follow, each a one-sided formula that is TRUE for valid rows and named with the message to show, e.g. list("Age is between 0 and 120" = ~ age >= 0 & age <= 120, "End is after the start" = ~ end >= start). Cells that break a rule are marked in the grid and listed in the Problems tab, and Done asks before returning data with problems. Rules can also be added from a column's menu (Rules...). See the Validation section.

formats

conditional formats: how to colour cells, without changing the data. A list of formats, each a one-sided formula or a list:

  • list(~ mpg > 25, fill = "#DCFCE7", color = "#166534", bold = TRUE): cells where the formula is TRUE get the fill, text colour and/or bold text (a formula alone gets a yellow fill). The cells of the columns the formula uses are coloured; give columns to colour other columns, or columns = "all" for whole rows;

  • list(scale = c("white", "#EF4444"), columns = "hp"): a colour scale shading numbers from the lowest to the highest value (two colours, or three for low, middle and high). limits = c(0, 300) fixes the values of the end colours and mid the middle one.

Names of the list are labels. When several formats colour a cell, the later one wins. Formats can also be added to a column from its menu (Conditional formatting...).

col_summary

logical indicating whether a summary of each column is shown under its header: a histogram of numbers and dates or the most common values, the share of missing values and the number of distinct values. Click a bar to show only those rows, the missing share to show the rows where the value is missing, or the number of values for the details (smallest, largest, mean, ...). Set to TRUE by default; the toolbar button hides the summaries.

row_names

logical indicating whether the row names of the data are shown in the editor, set to TRUE by default. When FALSE the row names are kept out of sight but still returned; rows added in the editor are named by their row number.

col_widths

widths of the columns in pixels: one number for every column, or numbers named by column, e.g. c(notes = 400, id = 60). Other columns are as wide as their values, up to 320 pixels; drag the edge of a column header to resize it.

page_rows, page_cols

number of rows and columns to show at a time, or NULL (the default) to show them all. The status bar has buttons to move between the pages, and Pages in the status bar changes the page sizes while editing. Pages only change what is on screen: filters, find, Done and exports cover every page.

...

not in use.

Value

the edited data as a matrix or data.frame. For database tables the edited rows are returned as a data.frame after the changes have been committed.

Editing

Double-click a cell to edit it. Click and drag to select a range of cells, then copy (Ctrl+C), paste (Ctrl+V), clear (Delete) or fill down (Ctrl+D). Right click a row to insert or delete rows, and right click a column header to insert, rename, hide or delete columns. Double-click a column's name to rename it. Ctrl+Z and Ctrl+Y undo and redo changes; press ? for the full list of shortcuts.

Layout

The toolbar opens other data (Open), shows or hides column summaries and columns, filters rows (Filter, a dialog listing every filter), lists active filters, searches the data (Ctrl+F), and opens the side panel. The panel shows the selected row as a form (Record), lists every change with a button to revert it, the history of changes, broken rules and the code that reproduces the edits. Under each column name is a summary of the column: click its bars to filter the rows, or type in the boxes under it. The status bar shows how many rows and columns are on screen and summarises the selected cells. The menu next to Done chooses whether all data or only what is on screen is returned.

Labelled data

Data read from SPSS, Stata or SAS files with haven keeps its variable labels (shown when hovering over a column name), value labels and SPSS user-defined missing values. Cells show each value with its label (1 Male), the cell editor offers the labels, and a label typed or pasted into a cell is stored as its value. Labels... in the column menu changes the variable label and value labels, and Change type turns labelled values into factors or text with their labels. The returned data and the generated code keep the labels.

Databases

Supply a dbplyr lazy table (e.g. dplyr::tbl(con, "artists")) or a db_table() to edit a database table. Rows are matched by primary key, changes are staged until you press Done, and you are asked to confirm before anything is written. Writes happen in a single transaction and are rolled back if any row was changed by someone else in the meantime. Adding, removing and renaming columns is disabled for database tables.

Change log and notes

Every change is recorded with the time and the user name. The History tab of the review panel lists the changes step by step and each step can be given a note, for example to say why a value was corrected. Supply log to keep this record in a file.

Drafts

With autosave = TRUE the changes are saved as a draft a moment after each edit. Drafts are kept in tools::R_user_dir("DataEditR", "data"); set options(DataEditR.drafts = ) to use another folder. A draft is removed when Done or Cancel is pressed, when it is restored or discarded, and after 30 days. Pressing Cancel asks for confirmation before changes are discarded.

Validation

Rules are checked after every change. Missing values pass a rule unless the rule says otherwise, so ~ end >= start only checks rows where both are filled in; add "Start is required" = ~ !is.na(start) to require a value. In the editor, a column's menu (Rules...) makes it required or unique, sets limits or a pattern, or adds a formula.

Column actions

A column's menu (or right-clicking its header) has actions that change the whole column: Formula... (a new column or new values from an R expression, e.g. round(mpg * 0.425, 1)), Find and replace..., Recode values..., Change type and sorting. Each shows a preview and is recorded as one dplyr verb, so the generated code reads mutate(kpl = round(mpg * 0.425, 1), .after = mpg) rather than listing every value. Formulas can use column names and common functions (arithmetic, round(), ifelse(), paste(), case_when(), as.Date(), ...), but not other code.

RStudio add-in

data_edit() is also available from the RStudio Addins menu as Interactive Data Editor. Highlight the name of a data frame, matrix or database table in the source editor or console and run the add-in to open it in the editor; with nothing highlighted an empty table is opened. The add-in can be bound to a keyboard shortcut through Tools > Modify Keyboard Shortcuts.

Author(s)

Dillon Hammill, [email protected]

Examples

if(interactive()) {

  data_edit(mtcars)

}

Shiny module for data editing

Description

dataEdit renders an editable, spreadsheet-like grid built on the MIT-licensed 'Tabulator' JavaScript library. Edits are sent to R as cell-level changes rather than whole tables, which keeps large datasets responsive and makes undo/redo, change tracking and database commits possible.

Usage

dataEditUI(
  id,
  height = "65vh",
  toolbar = TRUE,
  toolbar_left = NULL,
  toolbar_right = NULL
)

dataEditServer(
  id,
  data = reactive(NULL),
  col_bind = NULL,
  col_edit = TRUE,
  col_options = NULL,
  col_stretch = FALSE,
  col_names = TRUE,
  col_readonly = NULL,
  col_hide = NULL,
  col_factor = FALSE,
  row_bind = NULL,
  row_edit = TRUE,
  row_index = reactive(NULL),
  rows = NULL,
  columns = NULL,
  quiet = FALSE,
  read_fun = "read.csv",
  read_args = NULL,
  track = TRUE,
  code_name = "data",
  autosave = FALSE,
  user = NULL,
  col_actions = TRUE,
  rules = NULL,
  formats = NULL,
  col_summary = TRUE,
  history = NULL,
  row_names = TRUE,
  col_widths = NULL,
  page_rows = NULL,
  page_cols = NULL,
  ...
)

Arguments

id

unique identifier for the module to prevent namespace clashes when making multiple calls to this shiny module.

height

height of the grid as a valid CSS unit, set to "65vh" by default.

toolbar

logical indicating whether the toolbar (undo/redo, columns, find, review changes, code), review panel and status bar should be shown around the grid, set to TRUE by default.

toolbar_left, toolbar_right

optional UI elements to add at the start or end of the toolbar (data_edit() adds its Open and Export menus here).

data

a reactive expression containing an array (e.g. data.frame, matrix or data.table), a database table (see db_table) or a vector indicating the dimensions of the array (e.g. c(10,10)) or column names to construct a new template for editing. If no data is supplied a template with 10 rows and columns will be generated for editing.

col_bind

additional columns to add to the data prior to loading into editor, can be either an array containing the new data, a vector containing the new column names for empty columns or a named list containing a vector for each new column.

col_edit

logical indicating whether columns can be added or removed, set to TRUE by default.

col_options

a list named by column with the input to use for each column:

  • c(TRUE, FALSE) or "checkbox": checkboxes;

  • a vector of values, e.g. c("A", "B", "C"): a dropdown menu. Give the values names to show the names instead, as for shiny::selectInput(): list("New South Wales" = "NSW", "Victoria" = "VIC");

  • "dropdown": a dropdown menu of the values in the column (or the levels of a factor);

  • "date" or "datetime": a date or date-time picker (the column is returned as Date or POSIXct);

  • "time": a time picker ("HH:MM" text);

  • "textarea": text over several lines;

  • "password": hidden text;

  • "url": web addresses with a button to open them;

  • "html": cells shown as HTML (links, line breaks, bold, images, ...) without scripts or styles; double-click to edit the HTML;

  • "colour" (or "color"): colours (R colour names such as "grey50" or hex codes such as "#1D4ED8") shown with a swatch and edited with a colour picker. Set the colours the picker offers with list(type = "colour", palette = c("red", "#1D4ED8")); any colour can still be typed or picked;

  • c(min = 0, max = 10, step = 1) (any of the three): numbers within limits, in steps of step counted from min;

  • "integer": whole numbers, returned as integers (with limits: list(type = "integer", min = 0, max = 10));

  • "slider": a slider and bar for numbers from 0 to 100;

  • "rating": a rating from 0 to 5 stars.

Set the limits of a slider with c(type = "slider", min = 0, max = 1, step = 0.05) and the number of stars of a rating with c(type = "rating", stars = 10) (a list() works too). Values outside the limits or off the steps are marked in the editor and cannot be entered. Columns that are not in the data are ignored (with a message), here and in col_readonly, col_hide and col_widths, so the same settings can be used for different data. Unlike earlier versions, using col_options no longer disables adding or removing columns.

col_stretch

logical indicating whether columns should be stretched to fill the full width of the display, set to FALSE by default.

col_names

logical indicating whether column names can be edited or a vector of column names that cannot be edited, set to TRUE by default to allow editing of column names.

col_readonly

names of columns that cannot be edited. Values and names of these columns are locked in the grid.

col_hide

names of columns to hide from the editor. Hidden columns will not be visible or editable but will be retained in the data returned by the module.

col_factor

logical indicating whether character columns should be converted to factors prior to returning the edited data, set to FALSE by default. Factor columns in the data are always returned as factors with their levels; new values become new levels after the existing ones.

row_bind

additional rows to add to the data prior to loading into editor, can be either an array containing the new data, a vector containing the new row names for empty rows or a named list containing a vector for each new column.

row_edit

logical indicating whether rows can be added or removed, set to TRUE by default.

row_index

retained for backwards compatibility and no longer required. Rows now carry stable identifiers, so new rows are numbered automatically.

rows

a reactive expression returning the row indices (positions in the data returned by this module) to display, or NULL to display all rows. Edits made to the displayed subset are applied directly to the full data.

columns

a reactive expression returning the names of the columns to display, or NULL to display all columns.

quiet

logical to suppress messages and notifications.

read_fun

name of the function to use to read in the data when a file is selected, set to read.csv by default.

read_args

a named list of additional arguments to pass to read_fun when reading in files.

track

TRUE (the default) highlights cells that have been edited or added with a blue tint and border. Give a CSS colour (e.g. "#DC2626" or "red") to use another colour, or FALSE to turn the highlighting off.

code_name

name of the data used in the code shown in the review panel, set to "data" by default. Can also be a reactive expression returning the name. Two names, e.g. c("mtcars", "cars"), give the data the code starts from and the name the code assigns the result to.

autosave

logical indicating whether changes should be saved as a draft while editing, so that they can be restored if the app is closed before they are saved. When the same data is opened again by the same user, they are asked whether to restore the changes. Set to FALSE by default. Drafts are kept in tools::R_user_dir("DataEditR", "data") (or the folder set with options(DataEditR.drafts = )) and are removed when the changes are committed or after 30 days.

user

name of the person editing, recorded in the change log (see dataEditLog()). By default the user signed in to the app (session$user), the DataEditR.user option or the system user name.

col_actions

logical indicating whether the column menu offers actions that change a whole column: formulas, find and replace, recoding values, changing the type and sorting the rows. They are shown in the generated code as one dplyr verb each. Set to TRUE by default.

rules

a list of rules the data should follow, each a one-sided formula that is TRUE for valid rows, named with the message to show, e.g. list("End must be after the start" = ~ end >= start). Cells that break a rule are marked and listed in the Problems tab (see dataEditProblems()). Users can add rules to a column from its menu (Rules...).

formats

conditional formats: how to colour cells, without changing the data. A list of formats, each a one-sided formula or a list:

  • list(~ mpg > 25, fill = "#DCFCE7", color = "#166534", bold = TRUE): cells where the formula is TRUE get the fill, text colour and/or bold text (a formula alone gets a yellow fill). The cells of the columns the formula uses are coloured; give columns to colour other columns, or columns = "all" for whole rows;

  • list(scale = c("white", "#EF4444"), columns = "hp"): a colour scale shading numbers from the lowest to the highest value (two colours, or three for low, middle and high). limits = c(0, 300) fixes the values of the end colours and mid the middle one.

Names of the list are labels. When several formats colour a cell, the later one wins. Users can add formats to a column from its menu (Conditional formatting...).

col_summary

logical indicating whether a summary of each column (a histogram or the most common values, the share of missing values and the number of distinct values) is shown under its header, set to TRUE by default. Clicking a bar shows only those rows; the summaries can be hidden with the toolbar button.

history

the change log of earlier editing sessions to list in the History tab under the changes of this session: a data frame with the columns of dataEditLog() (at least step and action), or a reactive expression returning one. For example the entries returned by dataEditCommit() and written to a database table, read back with DBI::dbReadTable(). The session column tells the sessions apart (entries of the current session are left out). data_edit(log = "file.csv") reads the earlier sessions of the data from its file.

row_names

logical indicating whether the row names of the data are shown in the editor, set to TRUE by default. When FALSE the row names are kept out of sight but still returned; rows added in the editor are named by their row number.

col_widths

widths of the columns in pixels: one number for every column, or numbers named by column, e.g. c(notes = 400, id = 60). Other columns are as wide as their values, up to 320 pixels; drag the edge of a column header to resize it.

page_rows, page_cols

number of rows and columns to show at a time, or NULL (the default) to show them all. The status bar has buttons to move between the pages, and Pages in the status bar changes the page sizes while editing. Pages only change what is on screen: filters, find, Done and exports cover every page.

...

not in use.

Value

reactive expression containing the edited data. Pass it to dataEditCommit() to save the changes (e.g. write them to a database) and to dataEditChanges() for a summary of the changes that have not been saved yet. The reactive also carries the attribute "view", a reactive returning only the rows and columns on display.

Author(s)

Dillon Hammill, [email protected]

Examples

if (interactive()) {
  library(shiny)

  ui <- fluidPage(
    dataInputUI("input-1"),
    dataOutputUI("output-1"),
    dataEditUI("edit-1")
  )

  server <- function(input, output, session) {
    data_to_edit <- dataInputServer("input-1")
    data_edit <- dataEditServer("edit-1",
      data = data_to_edit
    )
    dataOutputServer("output-1",
      data = data_edit
    )
  }

  shinyApp(ui, server)
}

Save the changes made in a data editor

Description

dataEditCommit() saves the changes made in a data editor created by dataEditServer(), for example when the user presses a Save button in your shiny application. dataEditChanges() returns a summary of the changes that have not been saved yet, which is useful to enable a Save button or to ask the user to confirm. dataEditLog() returns the change log: every change made in the editor, with when it was made and by whom.

Usage

dataEditCommit(x)

dataEditChanges(x)

dataEditLog(x)

dataEditProblems(x)

Arguments

x

the reactive expression returned by dataEditServer().

Details

For database tables (see db_table()) the staged changes are written to the database in a single transaction: edited rows are updated, removed rows are deleted and new rows are inserted. If any row has been changed or removed by someone else since it was loaded, the whole commit is rolled back, nothing is written and an error of class "editr_conflict" is raised; the changes stay in the editor so the user can try again. After a successful commit the rows are loaded from the database again, so new rows show the keys generated by the database and the editor starts afresh.

For data in your R session (data frames, matrices, files, ...) nothing is written; the current data simply becomes the new starting point, so the review panel, change highlights and generated code start again from the committed data. Write the data returned by dataEditServer() wherever it needs to go in the same observer.

Value

dataEditCommit() invisibly returns a list with the number of rows updated, inserted and deleted, the number of columns added, removed or renamed and the log entries of the changes that were saved (NULL if no data is loaded). dataEditChanges() returns the same counts plus the number of edited cells and the total number of changes. dataEditLog() returns the change log. Both must be called in a reactive context (they update as the data is edited).

Change log

Every change made in the editor is recorded, one row per changed cell (or per row or column that was added, removed or renamed), in a data frame with the columns:

session

when the editing session started (e.g. "2026-11-02 09:27:27.123"), which names the session when logs of many sessions are kept together. Restoring a draft carries on its session.

time

when the change was made.

user

who made it (see the user argument of dataEditServer()).

step

number of the action the change belongs to. One action (typing a value, a paste, a fill, an undo, ...) is one step, the same unit that undo works with.

how

how the change was made: "edit", "paste", "fill", "shift" (cells inserted or deleted, moving the cells below), "clear", "undo", "redo" or "revert" (from the review panel), or the column action: "formula", "replace", "recode", "type" or "sort".

code

for column actions, the dplyr code of the action, e.g. mutate(kpl = mpg * 0.425).

action

"edit", "add row", "remove row", "add column", "remove column", "rename column", "change type" or "reorder rows".

row

the row name, the key of a database row or else the row number in the data that was opened (new rows are numbered after the last row).

column

the name of the column.

old, new

the values before and after, as text. For a removed row old lists the values of the whole row.

note

the note added to the step in the History tab, which users can use to say why a change was made.

Undoing a change is recorded as a new step, so the log is a complete record of what happened. The log is kept for the whole session, including across commits; the entries saved by a commit are returned by dataEditCommit() so that they can be written next to the data (for example to a log table in the same database).

Author(s)

Dillon Hammill, [email protected]

Examples

if (interactive() && requireNamespace("RSQLite", quietly = TRUE)) {
  library(shiny)

  con <- DBI::dbConnect(RSQLite::SQLite(), ":memory:")
  DBI::dbExecute(con, "CREATE TABLE cars (id INTEGER PRIMARY KEY,
    model TEXT, mpg REAL)")
  DBI::dbAppendTable(con, "cars", data.frame(
    model = rownames(mtcars), mpg = mtcars$mpg))

  ui <- bslib::page_fluid(
    shinyjs::useShinyjs(),
    dataEditUI(
      "cars",
      toolbar_right = actionButton("save", "Save", class = "btn-primary")
    )
  )

  server <- function(input, output, session) {
    cars <- dataEditServer("cars", data = dplyr::tbl(con, "cars"))

    # only enable saving when there is something to save
    observe({
      ch <- dataEditChanges(cars)
      shinyjs::toggleState("save", !is.null(ch) && ch$total > 0)
    })

    observeEvent(input$save, {
      res <- tryCatch(dataEditCommit(cars), editr_conflict = function(e) e)
      if (inherits(res, "editr_conflict")) {
        showNotification(conditionMessage(res), type = "error")
      } else {
        # keep a record of who changed what next to the data
        if (nrow(res$log) > 0) {
          DBI::dbWriteTable(con, "cars_log", res$log, append = TRUE)
        }
        showNotification(paste(res$updated, "updated,", res$inserted,
                               "added and", res$deleted, "removed"))
      }
    })
  }

  shinyApp(ui, server)
}

Shiny module for filtering data

Description

Shiny module for filtering data

Usage

dataFilterUI(id)

dataFilterServer(
  id,
  data = reactive(NULL),
  hide = FALSE,
  hover_text = NULL,
  reset = NULL
)

Arguments

id

unique identifier for the module to prevent namespace clashes when making multiple calls to this shiny module.

data

an array wrapped in reactive() containing the data to be filtered.

hide

logical indicating whether the data filtering user interface should be hidden from the user, set to FALSE by default.

hover_text

text to display on download button when user hovers cursor over button, set to NULL by default to turn off hover text.

reset

optional reactive expression that resets the filters whenever it changes. By default filters are reset whenever data changes; supply a separate trigger (e.g. the data input) to keep filters active while the data is being edited.

Value

a list of reactive objects containing the filtered data and indices for filtered rows.

Author(s)

Dillon Hammill, [email protected]

Examples

if (interactive()) {
  library(shiny)
  library(shinyjs)

  ui <- fluidPage(
    useShinyjs(),
    dataInputUI("input1"),
    dataFilterUI("filter1"),
    tableOutput("data1")
  )

  server <- function(input,
                     output,
                     session) {
    data_input <- dataInputServer("input1")
    
    # list with slots data and rows (indices)
    data_filter <- dataFilterServer("filter1",
      data = data_input
    )

    output$data1 <- renderTable({
      data_filter$data()
    })
    
  }

  shinyApp(ui, server)
}

Shiny module for data input

Description

Shiny module for data input

Usage

dataInputUI(id, cellWidths = c("50%", "48%"))

dataInputServer(
  id,
  data = NULL,
  read_fun = "read.csv",
  read_args = NULL,
  hide = FALSE,
  envir = parent.frame()
)

Arguments

id

unique identifier for the module to prevent namespace clashes when making multiple calls to this shiny module.

cellWidths

a vector of length 2 to control the relative widths of the fileInput and textInput, set to c("50%", "50%") by default.

data

can be either the name of a dataset or file as a character string (e.g. "mtcars" or "mtcars.csv") or a vector column names (e.g. c("A", "B", "C")) or template dimensions (e.g. c(10,10)).

read_fun

name of the function to use to read in the data when a file is selected, set to read.csv by default.

read_args

a named list of additional arguments to pass to read_fun when reading in files.

hide

logical indicating whether the data input user interface should be hidden from the user, set to FALSE by default.

envir

the environment in which to search for the supplied data, set to the parent.frame() of dataInput by default.

Author(s)

Dillon Hammill, [email protected]

Examples

if (interactive()) {
  library(shiny)

  ui <- fluidPage(
    dataInputUI("input1"),
    tableOutput("data1")
  )

  server <- function(input,
                     output,
                     session) {
    data_input1 <- dataInputServer("input1")

    output$data1 <- renderTable({
      data_input1()
    })
  }

  shinyApp(ui, server)
}

Shiny module for data output

Description

Shiny module for data output

Usage

dataOutputUI(id, icon = "download")

dataOutputServer(
  id,
  data = reactive(NULL),
  save_as = NULL,
  write_fun = "write.csv",
  write_args = NULL,
  hide = FALSE,
  hover_text = NULL
)

Arguments

id

unique identifier for the module to prevent namespace clashes when making multiple calls to this shiny module.

icon

supplied to dataOutputUI to control the appearance of the icon displayed on the download button, set to "download" by default.

data

an object of class data.frame wrapped in reactive to be saved to file.

save_as

name of the file to which the data should be saved, overrides input file path if supplied.

write_fun

name of the function to use when writing the data to file, set to "write.csv" by default.

write_args

a named list of additional arguments to pass to write_fun when reading in files.

hide

logical indicating whether the data input user interface should be hidden from the user, set to FALSE by default.

hover_text

text to display on download button when user hovers cursor over button, set to NULL by default to turn off hover text.

Value

dataOutputServer returns the data to be saved, wrapped in reactive.

Author(s)

Dillon Hammill, [email protected]

Examples

if (interactive()) {
  library(shiny)
  library(shinyjs)

  ui <- fluidPage(
    useShinyjs(),
    dataInputUI("input1"),
    dataOutputUI("output1"),
    tableOutput("data1")
  )

  server <- function(input,
                     output,
                     session) {
    data_input1 <- dataInputServer("input1")

    output$data1 <- renderTable({
      data_input1()
    })

    dataOutputServer("output1",
      data = data_input1
    )
  }

  shinyApp(ui, server)
}

Shiny module for selecting data

Description

Shiny module for selecting data

Usage

dataSelectUI(id)

dataSelectServer(
  id,
  data = reactive(NULL),
  hide = FALSE,
  hover_text = NULL,
  reset = NULL
)

Arguments

id

unique identifier for the module to prevent namespace clashes when making multiple calls to this shiny module.

data

an array wrapped in reactive() containing the data to be filtered.

hide

logical indicating whether the data selection user interface should be hidden from the user, set to FALSE by default.

hover_text

text to display on download button when user hovers cursor over button, set to NULL by default to turn off hover text.

reset

optional reactive expression that resets the selection whenever it changes. By default the selection is reset whenever data changes.

Value

a list of reactive objects containing the filtered data, indices for selected columns and the names of the selected columns.

Author(s)

Dillon Hammill, [email protected]

Examples

if (interactive()) {
  library(shiny)
  library(shinyjs)

  ui <- fluidPage(
    useShinyjs(),
    dataInputUI("input1"),
    dataSelectUI("select1"),
    tableOutput("data1")
  )

  server <- function(input,
                     output,
                     session) {
    data_input <- dataInputServer("input1")

    data_select <- dataSelectServer("select1",
      data = data_input
    )

    output$data1 <- renderTable({
      data_select$data()
    })

  }

  shinyApp(ui, server)
}

A shiny module to synchronise datasets

Description

The purpose of this module is to merge changes made to a subset of the data with the master copy of the data.

Usage

dataSyncUI(id)

dataSyncServer(
  id,
  data = reactive(NULL),
  data_subset = reactive(NULL),
  rows = reactive(NULL),
  columns = reactive(NULL),
  hide = FALSE,
  hover_text = NULL,
  auto = FALSE
)

Arguments

id

unique identifier for the module to prevent namespace clashes when making multiple calls to this shiny module.

data

master copy of the data.

data_subset

subset of data with altered entries.

rows

the row indices of data_subset within data.

columns

the column indices of data_subset within data.

hide

logical indicating whether the data synchronisation user interface should be hidden from the user, set to FALSE by default.

hover_text

text to display on download button when user hovers cursor over button, set to NULL by default to turn off hover text.

auto

logical indicating whether data synchronisation should happen automatically whenever data_subset changes. When TRUE, the sync button is not required. Set to FALSE by default for backward compatibility.

Author(s)

Dillon Hammill, [email protected]

Examples

if(interactive()){
 library(shiny)
 library(shinyjs)

 ui <- fluidPage(
   useShinyjs(),
   dataInputUI("input1"),
   dataFilterUI("filter1"),
   dataEditUI("edit1")
 )

 server <- function(input,
                    output,
                    session) {

   values <- reactiveValues(
     data = NULL,
     data_subset = NULL
   )

   data_input <- dataInputServer("input1")

  data_edit <- dataEditServer(
     "edit1",
     data = data_input
   )

   data_sync <- dataSyncServer(
     "sync1",
     data = data_input,
     data_subset = data_edit,
     rows = NULL,
     columns = NULL,
     auto = TRUE
   )

  }
 shinyApp(ui, server)
}

Edit a table in a database

Description

db_table() describes a database table for data_edit(). You can usually skip it and pass a dbplyr lazy table directly, e.g. data_edit(tbl(con, "artists")); use db_table() when the key cannot be detected automatically or the query is not a simple table reference.

Usage

db_table(
  x,
  table = NULL,
  key = NULL,
  limit = NULL,
  check = TRUE,
  readonly = NULL
)

Arguments

x

a dbplyr lazy table (e.g. dplyr::tbl(con, "artists"), optionally with filter(), select() or arrange() applied) or a DBI connection.

table

name of the table to write to, a character string or a DBI::Id(). Required when x is a connection, otherwise detected from the lazy table.

key

name(s) of the column(s) that uniquely identify each row. When NULL the primary key is detected for SQLite, DuckDB and PostgreSQL databases.

limit

maximum number of rows to load into the editor at a time, set to getOption("DataEditR.db_rows", 100000) by default. Use dplyr::filter() on the lazy table, or Rows in the editor, to choose which rows to load.

check

logical indicating whether updates and deletes should verify that rows have not changed in the database since they were loaded (optimistic concurrency), set to TRUE by default.

readonly

TRUE to open the table read-only, FALSE to stop with an error when it cannot be written to. Set to NULL by default to open queries that cannot be written to (SQL, joins, tables without a primary key) read-only.

Details

Rows are matched to the database through the key columns. Edits are staged in the editor and only written when you press Done and confirm the commit. All changes are written in a single transaction: if any row has been changed by someone else since it was loaded (or no longer exists), the whole commit is rolled back and nothing is written. Adding, removing and renaming columns is disabled for database tables.

Tables do not have to fit in memory: at most limit rows are loaded at a time, and Rows in the toolbar loads other rows (those matching a filter, in a chosen order), with the filter and sorting done by the database. Queries that cannot be written back (SQL, joins, or tables without a primary key, e.g. read_parquet() with DuckDB) are opened read-only, so large files can still be explored.

Value

an object of class editr_db_table to pass to data_edit() or dataEditServer().

Author(s)

Dillon Hammill, [email protected]

Examples

if (interactive() && requireNamespace("RSQLite", quietly = TRUE)) {
  con <- DBI::dbConnect(RSQLite::SQLite(), ":memory:")
  DBI::dbExecute(con, "CREATE TABLE cars (id INTEGER PRIMARY KEY,
    model TEXT, mpg REAL)")
  DBI::dbAppendTable(con, "cars", data.frame(
    model = rownames(mtcars), mpg = mtcars$mpg))

  # key detected automatically
  data_edit(dplyr::tbl(con, "cars"))

  # explicit table description
  data_edit(db_table(con, table = "cars", key = "id"))
}