I group the observations in a dataframe by ID. I want to keep the value of the first row in each group as it is, while fill in the remaining rows in the same group with lagged values + 2 and raise it to the power of 2. I want to update the lagged values as I proceed.
Please take the following dataset as an example:
ID <- c("1","1","1","2","2","3","3","3")
val <- c(1:8)
df <- data.frame(ID,val)
ID val
1 1 1
2 1 2
3 1 3
4 2 4
5 2 5
6 3 6
7 3 7
8 3 8
I am expecting to see:
ID val
1 1 1
2 1 (1 + 2)^2 = 9
3 1 (9 + 2)^2 = 121
4 2 4
5 2 (4 + 2)^2 = 36
6 3 6
7 3 (6 + 2)^2 = 64
8 3 (64 + 2)^2 = 4356
What I have tried:
df <- df %>% group_by(ID) %>% mutate(val = ifelse(row_number()!=1,(lag(val)+2)^2, val))
But what I seemed to get is:
ID val
1 1 1
2 1 (1 + 2)^2 = 9
3 1 (2 + 2)^2 = 16
4 2 4
5 2 (4 + 2)^2 = 36
6 3 6
7 3 (6 + 2)^2 = 64
8 3 (7 + 2)^2 = 81
I guess R does not update the value in the previous row before it proceeds to the next row, so it was using the old lagged value. Is there a way to fix this? Also, I have to apply similar but more complicated calculations (a lot of exponents) on a large dataset, so if there is a quick way, it will be perfect!
Thank you!