This site uses different types of cookies, including analytics and functional cookies (its own and from other sites). To change your cookie settings or find out more, click here. If you continue browsing our website, you accept these cookies.
If I've understood correctly, this is giving the result you want although I'm not calculating it in the same way.
What you seem to be doing is subtracting all values of A for a student from R until there is not enough remaining, then reducing R to 0 by subtracting R instead of A. I've done that by creating a running sum of A, filling in all values of R with the original value for the student, then subtracting the running sum from the previous row unless it exceeds R, in which case set R to 0 (this doesn't happen in your test data). I then create B from those values, although depending on what you're doing that might not be necessary.