Skip to content

Commit

Permalink
Implement add_row.
Browse files Browse the repository at this point in the history
Fixes #1021
  • Loading branch information
hadley committed Oct 29, 2015
1 parent 1fe5140 commit 8b29bfb
Show file tree
Hide file tree
Showing 4 changed files with 89 additions and 0 deletions.
1 change: 1 addition & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,7 @@ S3method(unique,sql)
S3method(update,tbl_sql)
export("%>%")
export(.datatable.aware)
export(add_row)
export(add_rownames)
export(anti_join)
export(arrange)
Expand Down
2 changes: 2 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# dplyr 0.4.3.9000

* New `add_row()` makes it easy to add a new row to data frame (#1021)

* New `lst()` and `lst_()` which create lists in the same way that
`data_frame()` and `data_frame_()` create data frames (#1290).

Expand Down
44 changes: 44 additions & 0 deletions R/dataframe.R
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,50 @@ add_rownames <- function(df, var = "rowname") {
bind_cols(rn, df)
}

#' Add a row to a data frame
#'
#' This is a convenient way to add a single row of data to an existing data
#' frame. See \code{\link{frame_data}} for an easy way to create an complete
#' data frame row-by-row.
#'
#' @param .data Data frame to append to.
#' @param ... Name-value pairs. If you don't supply the name of a variable,
#' it'll be given the value \code{NA}.
#' @examples
#' # add_row ---------------------------------
#' df <- data_frame(x = 1:3, y = 3:1)
#'
#' df %>%
#' add_row(x = 4, y = 0)
#'
#' # You can supply vectors, to add multiple rows (this isn't
#' # recommended because it's a bit hard to read)
#' df %>%
#' add_row(x = 4:5, y = 0:-1)
#'
#' # Absent variables get missing values
#' df %>%
#' add_row(x = 4)
#'
#' # You can't create new variables
#' \dontrun{
#' df %>%
#' add_row(z = 10)
#' }
#' @export
add_row <- function(.data, ...) {
df <- data_frame(...)

extra_vars <- setdiff(names(df), names(.data))
if (length(extra_vars) > 0) {
stop(
"This row would add new variables: ", paste0(extra_vars, collapse = ", "),
call. = FALSE
)
}

bind_rows(.data, data_frame(...))
}

# Validity checks --------------------------------------------------------------

Expand Down
42 changes: 42 additions & 0 deletions man/add_row.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 8b29bfb

Please sign in to comment.