1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
|
#' Add rows to a data frame
#'
#' @description
#' This is a convenient way to add one or more rows of data to an existing data
#' frame. See [tribble()] for an easy way to create an complete
#' data frame row-by-row. Use [tibble_row()] to ensure that the new data
#' has only one row.
#'
#' `add_case()` is an alias of `add_row()`.
#'
#' @param .data Data frame to append to.
#' @param ... <[`dynamic-dots`][rlang::dyn-dots]>
#' Name-value pairs, passed on to [tibble()]. Values can be defined
#' only for columns that already exist in `.data` and unset columns will get an
#' `NA` value.
#' @param .before,.after One-based row index where to add the new rows,
#' default: after last row.
#' @family addition
#' @examples
#' # add_row ---------------------------------
#' df <- tibble(x = 1:3, y = 3:1)
#'
#' df %>% add_row(x = 4, y = 0)
#'
#' # You can specify where to add the new rows
#' df %>% add_row(x = 4, y = 0, .before = 2)
#'
#' # 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)
#'
#' # Use tibble_row() to add one row only
#' df %>% add_row(tibble_row(x = 4, y = 0))
#' try(df %>% add_row(tibble_row(x = 4:5, y = 0:-1)))
#'
#' # Absent variables get missing values
#' df %>% add_row(x = 4)
#'
#' # You can't create new variables
#' try(df %>% add_row(z = 10))
#' @export
add_row <- function(.data, ..., .before = NULL, .after = NULL) {
if (inherits(.data, "grouped_df")) {
cnd_signal(error_add_rows_to_grouped_df())
}
if (!is.data.frame(.data)) {
deprecate_warn("2.1.1", "add_row(.data = 'must be a data frame')")
}
if (dots_n(...) == 0L) {
# A single row of missing values is added if no input is supplied
df <- new_tibble(list(), nrow = 1L)
} else {
df <- tibble(...)
}
extra_vars <- setdiff(names(df), names(.data))
if (has_length(extra_vars)) {
cnd_signal(error_incompatible_new_rows(extra_vars))
}
pos <- pos_from_before_after(.before, .after, nrow(.data))
out <- rbind_at(.data, df, pos)
vectbl_restore(out, .data)
}
#' @export
#' @rdname add_row
#' @usage NULL
add_case <- add_row
na_value <- function(boilerplate) {
if (is.list(boilerplate)) {
list(NULL)
} else {
NA
}
}
rbind_at <- function(old, new, pos) {
out <- vec_rbind(old, new)
# Append at end: Nothing more to do.
if (pos >= nrow(old)) {
return(out)
}
# Splice: Construct index vector
pos <- max(pos, 0L)
idx <- c(
seq2(1L, pos),
seq2(nrow(old) + 1L, nrow(old) + nrow(new)),
seq2(pos + 1L, nrow(old))
)
vec_slice(out, idx)
}
#' Add columns to a data frame
#'
#' This is a convenient way to add one or more columns to an existing data
#' frame.
#'
#' @param .data Data frame to append to.
#' @param ... <[`dynamic-dots`][rlang::dyn-dots]>
#' Name-value pairs, passed on to [tibble()]. All values must have
#' the same size of `.data` or size 1.
#' @param .before,.after One-based column index or column name where to add the
#' new columns, default: after last column.
#' @inheritParams tibble
#' @family addition
#' @examples
#' # add_column ---------------------------------
#' df <- tibble(x = 1:3, y = 3:1)
#'
#' df %>% add_column(z = -1:1, w = 0)
#' df %>% add_column(z = -1:1, .before = "y")
#'
#' # You can't overwrite existing columns
#' try(df %>% add_column(x = 4:6))
#'
#' # You can't create new observations
#' try(df %>% add_column(z = 1:5))
#'
#' @export
add_column <- function(.data, ..., .before = NULL, .after = NULL,
.name_repair = c("check_unique", "unique", "universal", "minimal")) {
if (!is.data.frame(.data)) {
deprecate_warn("2.1.1", "add_column(.data = 'must be a data frame')")
}
if (has_length(.data) && (!is_named(.data) || anyDuplicated(names2(.data))) && missing(.name_repair)) {
deprecate_warn("3.0.0", "add_column(.data = 'must have unique names')",
details = 'Use `.name_repair = "minimal"`.'
)
.name_repair <- "minimal"
}
df <- tibble(..., .name_repair = .name_repair)
if (ncol(df) == 0L) {
return(.data)
}
if (nrow(df) != nrow(.data)) {
if (nrow(df) == 1) {
df <- df[rep(1L, nrow(.data)), ]
} else {
cnd_signal(error_incompatible_new_cols(nrow(.data), df))
}
}
pos <- pos_from_before_after_names(.before, .after, colnames(.data))
end_pos <- ncol(.data) + seq_len(ncol(df))
indexes_before <- rlang::seq2(1L, pos)
indexes_after <- rlang::seq2(pos + 1L, ncol(.data))
indexes <- c(indexes_before, end_pos, indexes_after)
new_data <- .data
new_data[end_pos] <- df
out <- new_data[indexes]
out <- set_repaired_names(out, repair_hint = TRUE, .name_repair)
vectbl_restore(out, .data)
}
# helpers -----------------------------------------------------------------
pos_from_before_after_names <- function(before, after, names) {
before <- check_names_before_after(before, names)
after <- check_names_before_after(after, names)
pos_from_before_after(before, after, length(names))
}
pos_from_before_after <- function(before, after, len) {
if (is.null(before)) {
if (is.null(after)) {
len
} else {
limit_pos_range(after, len)
}
} else {
if (is.null(after)) {
limit_pos_range(before - 1L, len)
} else {
cnd_signal(error_both_before_after())
}
}
}
limit_pos_range <- function(pos, len) {
max(0L, min(len, pos))
}
# check_names_before_after ------------------------------------------------
check_names_before_after <- function(j, x) {
if (!is_bare_character(j)) {
return(j)
}
check_needs_no_dim(j)
check_names_before_after_character(j, x)
}
check_needs_no_dim <- function(j) {
if (needs_dim(j)) {
cnd_signal(error_dim_column_index(j))
}
}
check_names_before_after_character <- function(j, names) {
pos <- safe_match(j, names)
if (anyNA(pos)) {
unknown_names <- j[is.na(pos)]
cnd_signal(error_unknown_column_names(unknown_names))
}
pos
}
# Errors ------------------------------------------------------------------
error_add_rows_to_grouped_df <- function() {
tibble_error("Can't add rows to grouped data frames.")
}
error_incompatible_new_rows <- function(names) {
tibble_error(
problems(
"New rows can't add columns:",
cnd_message(error_unknown_column_names(names))
),
names = names
)
}
error_both_before_after <- function() {
tibble_error("Can't specify both `.before` and `.after`.")
}
error_unknown_column_names <- function(j, parent = NULL) {
tibble_error(pluralise_commas("Can't find column(s) ", tick(j), " in `.data`."), j = j, parent = parent)
}
error_incompatible_new_cols <- function(n, df) {
tibble_error(
bullets(
"New columns must be compatible with `.data`:",
x = paste0(
pluralise_n("New column(s) ha[s](ve)", ncol(df)), " ",
nrow(df), " rows"
),
i = pluralise_count("`.data` has ", n, " row(s)")
),
expected = n,
actual = nrow(df)
)
}
|