Dynamic variable names in R

Viewed 29

I have the column a1, a2, a3 in my matrix. Now I want to generate a1_median, a2_median, a3_median in the same matrix by calculating the median of every column.

I tried to generate it with the following code, but it didn't work. It gives me the median of a1 for every column:

data[, (paste0("a",0:4, "_median")):= median(eval(parse(text = paste0("data$f",0:4, "_ltd"))))]

Is there another way to solve it?

1 Answers

Assuming it is a data.table, we need to loop over the columns as median expects a vector as input - specify the column names in .SDcols, loop over the Subset of data.table (.SD) with lapply, get the median and assign (:=) the columns to the new columns

nm1 <- paste0("f", 0:4, "_ltd")
# Based on the description, it says column names as 'a1', 'a2', 'a3'
# nm1 <- paste0("a", 1:4)
# median_cols <- paste0(nm1, "_median")
median_cols <- paste0("a", 0:4, "_median")
library(data.table)
setDT(data)[, (median_cols) := lapply(.SD, median, na.rm = TRUE), .SDcols = nm1]
Related