Context
I want calculate cumulative mean row-wise, on different sets of columns defined by pattern in the column names.
Example data, with two sets of columns starting with a and b, respectively:
a1 = c(1, 2, 3)
a2 = c(4, 5, 6)
a3 = c(7, 8, 9)
a4 = c(10, 11, 12)
b1 = c(10, 20, 30)
b2 = c(40, 50, 60)
b3 = c(70, 80, 90)
b4 = c(100, 110, 120)
df = data.frame(a1, a2, a3, a4, b1, b2, b3, b4)
> df
a1 a2 a3 a4 b1 b2 b3 b4
1 1 4 7 10 10 40 70 100
2 2 5 8 11 20 50 80 110
3 3 6 9 12 30 60 90 120
The first set of calculations is performed among the columns where the names start with an a:
a1_2 is the mean value of a1 and a2.
a1_3 is the mean value of a1, a2 and a3.
a1_4 is the mean value of a1, a2, a3 and a4.
Similarly, I want to perform the same calculations on the "b columns": b1_2, b1_3 and b1_4 are calculated in exactly the same way as a1_2, a1_3 and a1_4.
I can generate a1_2 to b1_4 with the following code. But in the real case I have too many similar variables to generate.
library(dplyr)
df %>%
rowwise() %>%
mutate(a1_2 = mean(c(a1, a2)),
a1_3 = mean(c(a1, a2, a3)),
a1_4 = mean(c(a1, a2, a3, a4)),
b1_2 = mean(c(b1, b2)),
b1_3 = mean(c(b1, b2, b3)),
b1_4 = mean(c(b1, b2, b3, b4))) %>%
ungroup()
a1 a2 a3 a4 b1 b2 b3 b4 a1_2 a1_3 a1_4 b1_2 b1_3 b1_4
1 1 4 7 10 10 40 70 100 2.5 4 5.5 25 40 55
2 2 5 8 11 20 50 80 110 3.5 5 6.5 35 50 65
3 3 6 9 12 30 60 90 120 4.5 6 7.5 45 60 75
Question
How can I perform these calculations more efficiently, without having to generate them one by one manually? These generated variables have a pattern, and the pattern is to calculate the average of multiple variables.
What I've done
I checked a question related to mine (Need to create multiple new variables simultaneously using across() in R). But in this question, the new variables generated by the author are not related to the other variables in the data frame, which is not the same as the problem I encountered.