[R] From strings to column names

Naresh Gurbuxani n@re@h_gurbux@n| @end|ng |rom hotm@||@com
Wed Jun 18 12:27:37 CEST 2025


My data.table has many columns in groups of four.  On each group, I want
to perform the same set of calculations.

mydt <- data.table(
date = seq(as.IDate("2025-06-01"), by = 1, length.out = 10),
ABC1_price = runif(10, 100, 120), ABC1_volume = runif(10, 200, 300),
ABC2_price = runif(10, 100, 120), ABC2_volume = runif(10, 200, 300),
DEF1_price = runif(10, 100, 120), DEF1_volume = runif(10, 200, 300),
DEF2_price = runif(10, 100, 120), DEF2_volume = runif(10, 200, 300))

mydt[
, let(ABC_price = fifelse(ABC1_volume < ABC2_volume, ABC2_price,
ABC1_price),
DEF_price = fifelse(DEF1_volume < DEF2_volume, DEF2_price, DEF1_price))
]

# Now use mydt[, list(ABC_price, DEF_price)] for subsequent calculations

With many columns, above method is error-prone and tedious.  Is it
possible to do something like:

myvars <- c("ABC", "DEF")
for (avar in myvars) {
# code for above calculations
}

Thanks,
Naresh



More information about the R-help mailing list