I was wondering if there was a more terse way of manipulating variables (in my context dividing) variables that have near identical names.
Please consider the following dataset:
library(data.table)
n = 100
DT <- data.table(id = seq(1, n),
A1 = rnorm(n), A2 = rnorm(n), A3 = rnorm(n),
B1 = rnorm(n), B2 = rnorm(n), B3 = rnorm(n),
C1 = rnorm(n), C2 = rnorm(n), C3 = rnorm(n))
Here, there are 9 variables with the following pattern: There are string identifiers (the "A", "B", "C") and there are number identifiers (1,2,3). I would like to create variables that divide the various variables within the string identifiers like the following (if I were to do it manually):
DT[, `:=`(A_1_2 = A1/A2, A_1_3 = A1/A3, A_2_3 = A2/A3,
B_1_2 = B1/B2, B_1_3 = B1/B3, B_2_3 = B2/B3,
C_1_2 = C1/C2, C_1_3 = C1/C3, C_2_3 = C2/C3)]
Of course, with a smaller dataset, a manual approach is simple and easy. The problem is that the data is large in both the length of unique string and integer identifiers.