Reputation: 1850
My data.table consists of an a priori unknown number of columns, eg.
DT <- data.table("columnPred" = c(1,2,3),
"column1" = c(7,8,9),
"column2" = c(44,55,66))
I would like to calculate the change between the columns, ie.
DT[, delta1 := ((columnPred/column1)-1)*100]
DT[, delta2 := ((column1/column2)-1)*100]
How can I do this when the number of columns is unknown ahead of time?
Upvotes: 1
Views: 219
Reputation: 1075
Using data.table
, and doing element-wise division on DT (with the right-most column removed on the numerator, left-most on the denominator).
delta_col_names <- paste0("delta",1:(ncol(DT)-1))
DT[, (delta_col_names) := ((DT[,1:(ncol(DT)-1)] / DT[,-1])-1)*100]
columnPred column1 column2 delta1 delta2
1: 1 7 44 -85.71429 -84.09091
2: 2 8 55 -75.00000 -85.45455
3: 3 9 66 -66.66667 -86.36364
Upvotes: 3