do_cols_dt: Perform operations on selected columns in a data.table

View source: R/dt_ops.R

do_cols_dtR Documentation

Perform operations on selected columns in a data.table

Description

This function performs arithmetic or other operations on a subset of columns in a data.table. It wraps the specified column names in backticks, concatenates them using the provided operator, and optionally applies a function to the resulting expression.

Usage

do_cols_dt(dtb, cols_to_add, symbol = c(",", "+", "-", "*", "/"), fn = NULL)

Arguments

dtb

A data.table.

cols_to_add

A character vector of column names to be operated on.

symbol

A character string specifying the operator to use between the columns. Defaults to '+' (if a vector is provided, the first element is used). Other examples include '-', '*', '/', or ','.

fn

An optional function name as a string. If provided, the operator expression is wrapped inside this function call.

Value

A data.table with one column containing the result of the evaluated expression.

Examples

## Not run: 
library(data.table)
dtb <- data.table(a = 1:5, b = 6:10)
# Sum columns a and b
do_cols_dt(dtb, c("a", "b"), symbol = "+")

# Multiply columns a and b
do_cols_dt(dtb, c("a", "b"), symbol = "*")

# Apply the sum function to the columns
do_cols_dt(dtb, c("a", "b"), symbol = "+", fn = "sum")

## End(Not run)

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