replace_from_table: Replace multiple values in a data.table column

View source: R/misc_functions.R

replace_from_tableR Documentation

Replace multiple values in a data.table column

Description

'replace_from_table' replace multiple values in a data.table column. . The values in from argument are matched and replaced by those in to argument. If newcolname = NULL the replace is by reference.

Usage

replace_from_table(dtb, colname, from, to, newcolname = NULL)

Arguments

dtb

A data.table to be changed by reference.

colname

A string denoting the name of the column to be changed.

from

A vector with values in colname to be replaced.

to

A vector with values in colname to be replaced.

newcolname

A string denoting the name of a new column to be created. If present, colname is not altered. If newcolname = NULL, colname is altered by reference

Value

a data.table, invisibly.

Examples

library(data.table)
library(CKutils)
dtb <- data.table::data.table("a" = 1:5, "b" = seq(1, 2.2, 0.3),
 "d" = letters[1:5])
dtb[, e := factor(a, labels = LETTERS[1:5])]
replace_from_table(data.table::copy(dtb), "a", 1:3, 3L)[]
replace_from_table(data.table::copy(dtb), "a", 3L, -11L)[]
replace_from_table(data.table::copy(dtb), "a", 3L, -11L, "newcol")[]
replace_from_table(data.table::copy(dtb), "b", 1.3, "a")[]
replace_from_table(data.table::copy(dtb), "b", 1.3, "a", "newcol")[]
replace_from_table(data.table::copy(dtb), "d", "a", "7")[]
replace_from_table(data.table::copy(dtb), "d", "a", 7)[]
replace_from_table(data.table::copy(dtb), "e", "B", "J")[]

ChristK/CKutils documentation built on April 11, 2025, 10:11 p.m.