R: Add variables or cases to data frames

add_variables {sjmisc} | R Documentation

## Add variables or cases to data frames

### Description

`add_variables()` adds a new column to a data frame, while `add_cases()` adds a new row to a data frame. These are convenient functions to add columns or rows not only at the end of a data frame, but at any column or row position. Furthermore, they allow easy integration into a pipe-workflow.

### Usage

    add_variables(data, ..., .after = Inf, .before = NULL)

    add_case(data, ..., .after = Inf, .before = NULL)

### Arguments

`data` | A data frame. For `add_columns()`, will be bound after data frames specified in `...`. For `replace_columns()`, duplicated columns in `data` will be replaced by columns in `...`.
`...` | One or more names vectors that indicate the variables or values, which will be added as new column or row to `data`. For `add_cases()`, non-matching columns in `data` will be filled with `NA`.
`.after, .before` | Numerical index of row or column, after or infront of what the new variable or case should be added. If `.after = -1`, variables or cases are added at the beginning; if `.after = Inf`, variables and cases are added at the end. In case of `add_variables()`, `.after` and `.before` may also be a character name indicating the column in `data`, after or infront of what `...` should be inserted.

### Value

`data`, including the new variables or cases from `...`.

### Note

For `add_case()`, if variable does not exist, a new variable is created and existing cases for this new variable get the value `NA`. See 'Examples'.

### Examples

    d <- data.frame(
      a = c(1, 2, 3),
      b = c("a", "b", "c"),
      c = c(10, 20, 30),
      stringsAsFactors = FALSE
    )

    add_case(d, b = "d")
    add_case(d, b = "d", a = 5, .before = 1)

    # adding a new case for a new variable
    add_case(d, e = "new case")

    add_variables(d, new = 5)
    add_variables(d, new = c(4, 4, 4), new2 = c(5, 5, 5), .after = "b")

[Package sjmisc version 2.7.5 Index]