I need to combine sets of variables ending in specific characters. The variables are named in the following way (data=df):
id A_1 A_2 A_3 B_1 B_2 B_3 C_1 C_2 C_3
1 7 2 1 6 7 4 3 9 0
2 8 5 2 9 7 2 1 6 1
3 5 4 0 8 6 4 1 7 0
Now let's say "combine" means that I need the rowMeans of every set of variables ending in _1, in _2 and so forth.
So I could do just this:
rowMeans(df[,c("A_1","B_1","C_1")])
rowMeans(df[,c("A_2","B_2","C_2")])
rowMeans(df[,c("A_3","B_3","C_3")])
The issue is that I have lots of these variable endings and I would essentially end up with one line of code per ending. Hence, I was wondering if there is a smarter way of doing the same thing using a for-loop.
This for-loop would need to contain i(1:n) for the ending and a stable name pattern which is "A_", "B_" and "C_" and then run rowMeans()
. But since I'm not an expert on writing loops, I have no idea how I would do this in practice.