I want to perform something like this.
a <- data.frame(A=c(1,5,9),
B=c(2,6,10),
C=c(3,7,11),
D=c(4,8,12))
a <- a %>% rowwise()
a <- a %>% mutate(mean(c_across(1:2)))
a <- a %>% mutate(mean(c_across(1:3)))
a <- a %>% mutate(mean(c_across(1:4)))
This gives:
A B C D mean(c_across(1:2)) mean(c_across(1:3)) mean(c_across(1:4))
1 2 3 4 1.5 2 2.5
5 6 7 8 5.5 6 6.5
9 10 11 12 9.5 10 10.5
I would like to get the same results using a for loop. I tried this:
a <- data.frame(A=c(1,5,9),
B=c(2,6,10),
C=c(3,7,11),
D=c(4,8,12))
a <- a %>% rowwise()
for(i in 2:4){
a <- a %>% mutate(mean(c_across(1:i)))
}
But it only shows the results of last value of i=4
A B C D mean(c_across(1:i))
1 2 3 4 2.5
5 6 7 8 6.5
9 10 11 12 10.5
Can anyone explain what is happening? Whenever I use a for loop when using dplyr, I immediately feel like I am doing something wrong. Is there any other better approach to this?