mutate_by_ref: Mutate multiple cols by reference using the same function

View source: R/mutate_by_ref.R

mutate_by_refR Documentation

Mutate multiple cols by reference using the same function

Description

Mutate multiple cols by reference using the same function

Usage

mutate_by_ref(DT, cols, f, names.extra = NULL)

Arguments

DT

a data.table

cols

a character vector of column names or a function that returns a logical vector to choose the column names

f

a function that will be used to mutate the columns

names.extra

if NULL (the default), then cols will be updated by reference in plcace. If names.extra is a character string, then new columns will be appended to DT with the names formed by paste0(var, names.extra). If names.extra is set to TRUE, then new columns will be appended to DT with the names paste0(var, ".", f), where f is the name of the function passed by the user and is found using deparse(substitute(f))

Examples

data(mtcars)

DT.mtcars <- as.data.table(mtcars)

##Add some columns for testing
DT.mtcars <- DT.mtcars %>%
  .[, mpg.char := as.character(mpg)] %>%
  .[, cyl.fact := as.factor(cyl)]

## mutate in place by reference
mutate_by_ref(copy(DT.mtcars),
              cols = c("mpg", "hp"), f = sqrt) %>%
  head %>% print

## mutate with new column names by reference
mutate_by_ref(copy(DT.mtcars),
              cols = c("mpg", "hp"), f = sqrt, names.extra = ".sqrt") %>%
  head %>% print

## mutate with new column names by reference
## setting `names.extra` to TRUE will use `deparse(substitute(f))` to
## get the name of f to use as `names.extra` and sepearte with a dot (`.`)
mutate_by_ref(copy(DT.mtcars),
              cols = c("mpg", "hp"), f = sqrt, names.extra = TRUE) %>%
  head %>% print

##mutate all numeric columns in place by reference
mutate_by_ref(copy(DT.mtcars),
              cols = is.numeric, f = sqrt) %>%
  head %>% print

##mutate all numeric columns with new names by reference
mutate_by_ref(copy(DT.mtcars),
              cols = is.numeric, f = sqrt, names.extra = ".sqrt") %>%
  head %>% print

##mutate all numeric columns with new names by reference
##setting `names.extra` to TRUE
mutate_by_ref(copy(DT.mtcars),
              cols = is.numeric, f = sqrt, names.extra = TRUE) %>%
  head %>% print

ChandlerLutz/CLmisc documentation built on Dec. 2, 2022, 12:40 p.m.