I need to calculate a New value based on Value2 and the newly created previous value of the same New column.
But additionally I want to do this per Group.
I made a for loop previously but it stopped working when i added a second loop for the groups.
for(j in 1:(*EACHGROUP*){
for(i in 2:nrow(DAT) #Start at second place in each Group
DAT$New[i] <- ( DAT$New[i-1]*10^(DAT$Value2[i]) )}
Dummy data
Year <- c(1980,1990,2000,2005,1993,2008,1999,2003,2005)
Group <- c("A","A","A","A","B","B","C","C","C")
Value2 <- c(0,0.25,0.1,-0.3,.5,0.7,-0.8,0.01,0.2)
New <- c(1,1,1,1,1,1,1,1,1)
DAT <- data.frame(cbind(Year,Group,Value2,New))
Output:
Year Group Value2 New
1 1980 A 0 1
2 1990 A 0.25 1
3 2000 A 0.1 1
4 2005 A -0.3 1
5 1993 B 0.5 1
6 2008 B 0.7 1
7 1999 C -0.8 1
8 2003 C 0.01 1
9 2005 C 0.2 1
How can I continue with this approach?
Or should I use "dplyr" for example to do this more easily?
Desired result
Year Group Value2 New
1 1980 A 0 1
2 1990 A 0.25 1.78
3 2000 A 0.1 2.24
4 2005 A -0.3 1.12
5 1993 B 0.5 1
6 2008 B 0.7 5.01
7 1999 C -0.8 1
8 2003 C 0.01 1.02
9 2005 C 0.2 1.62
Best regards
question from:
https://stackoverflow.com/questions/65923016/r-looping-through-rows-per-factor-with-a-function 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…