Including A Group Statement within a For Loop

Hello,

I'm looking to include a group statement within my for loop and I'm having difficulty finding any details into how to properly do this.

The example below , calculates the Extra, Outstanding and Current Column within a loop statement. I'm trying to group by id so that the loop will restart with every id. My current code:

dat <- tibble(
id = c("A","A","A","A","A","A","B","B"),
rn= c(1,2,3,4,5,6,1,2),
current = c(100,0,0,0,0,0,500,0),
paid = c(10,12,12,13,13,13,20,20),
pct_extra = c(.02,.05,.05,.07, .03, .01, .09,.01),
Extra = NA,
Outstanding = NA
)
for(i in 1:nrow(dat)){
dat$Extra[i] <- dat$current[i]*dat$pct_extra[i]
dat$Outstanding[i] <- dat$current[i] - dat$paid[i] - dat$Extra[i]
if(i < nrow(dat)){
dat$current[(i+1)] <- dat$Outstanding[i]
}
}

What I've tried:

for(i in 1:nrow(dat)){
dat%>%
group_by(id)%>%
mutate(Extra=pct_extra*(current-paid),
Outstanding=current-paid-Extra,
current=if_else(rn==1,current,lag(Outstanding)))}

Does anyone have an idea where/how I can include a group statement that will work within my current for loop? Thanks!

Is this what you mean? I'm not sure to understand your logic.

library(tidyverse)

dat <- tibble(
    id = c("A","A","A","A","A","A","B","B"),
    rn= c(1,2,3,4,5,6,1,2),
    current = c(100,0,0,0,0,0,500,0),
    paid = c(10,12,12,13,13,13,20,20),
    pct_extra = c(.02,.05,.05,.07, .03, .01, .09,.01)
)

dat %>% 
    group_by(id) %>% 
    mutate(Extra = current * pct_extra,
           Outstanding = current - paid - Extra,
           current = if_else(is.na(lag(Outstanding)), current, lag(Outstanding)))
#> # A tibble: 8 x 7
#> # Groups:   id [2]
#>   id       rn current  paid pct_extra Extra Outstanding
#>   <chr> <dbl>   <dbl> <dbl>     <dbl> <dbl>       <dbl>
#> 1 A         1     100    10      0.02     2          88
#> 2 A         2      88    12      0.05     0         -12
#> 3 A         3     -12    12      0.05     0         -12
#> 4 A         4     -12    13      0.07     0         -13
#> 5 A         5     -13    13      0.03     0         -13
#> 6 A         6     -13    13      0.01     0         -13
#> 7 B         1     500    20      0.09    45         435
#> 8 B         2     435    20      0.01     0         -20

Created on 2021-03-04 by the reprex package (v1.0.0.9002)

If this is not what you are trying to do, please try to provide a proper REPRoducible EXample (reprex) illustrating your issue and include a sample of your desired output as well.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.