user3651829 user3651829 - 2 months ago 7
R Question

Referencing incremental variables in r

I have a number of variables such as

A1 A2 A3 A4
and
B1 B2 B3 B4
and
C1 C2 C3 C4
. I am trying to
cbind
these together into a data frame but the number of variables for
A
,
B
and
C
varies each run. So here the maximum for each is 4, but other times it may be 10 for example.

df <- cbind(A1,A2,A3,A4,B1,B2,B3,B4,C1,C2,C3,C4)

df <- cbind(A1-Amax,B1-Bmax,C1-Cmax)


where
max
is a variable containing the max number (i.e 4 in this example).

Answer

We can try with mget to get a list output

res <- do.call(cbind, mget(ls(pattern = "(A|B|C)\\d+")))

Suppose if we need it separate to calculate the "Aamax", "Bbmax" etc.

lstA <- mget(ls(pattern = "A\\d+"))
lstB <- mget(ls(pattern = "B\\d+"))
lstC <- mget(ls(pattern = "C\\d+"))

It is not clear what the "Aamax", "Bbmax" etc.

Comments