Learn R Programming

sjmisc (version 2.3.0)

add_columns: Add columns to a data frame

Description

This function combines two or more data frames, but unlike cbind or bind_cols, this function binds data as last columns of a data frame.

Usage

add_columns(data, ..., replace = TRUE)

Arguments

data
A data frame. Will be bound after data frames specified in ....
...
More data frames to combine.
replace
Logical, if TRUE (default), columns in ... with identical names in data will replace the columns in data. The order of columns after replacing is preserved.

Value

A data frame, where columns of data are appended after columns of ....

Examples

Run this code
data(efc)
d1 <- efc[, 1:3]
d2 <- efc[, 4:6]

library(dplyr)
head(bind_cols(d1, d2))
add_columns(d1, d2)

d1 <- efc[, 1:3]
d2 <- efc[, 2:6]

add_columns(d1, d2, replace = TRUE)
add_columns(d1, d2, replace = FALSE)

# use case: we take the original data frame, select specific
# variables and do some transformations or recodings
# (standardization in this example) and add the new, transformed
# variables *to the end* of the original data frame
efc %>%
  select(e17age, c160age) %>%
  std() %>%
  add_columns(efc)

# new variables with same name will overwrite old variables
# in "efc". order of columns is not changed.
efc %>%
  select(e16sex, e42dep) %>%
  to_factor() %>%
  add_columns(efc)

# keep both old and new variables, automatically
# rename variables with identical name
efc %>%
  select(e16sex, e42dep) %>%
  to_factor() %>%
  add_columns(efc, replace = FALSE)

Run the code above in your browser using DataLab