library(tidyverse)
data=tibble(lender=c('Tony','Wood','Tony','Tidy'),borrower=c('Wood','Tony','Wood','Tony'),amount=c(1,2,3,4))
It's a simple table. I want to calculate the net amount for Tony.
For example, in the first row,Tony lend Wood 1,so it should be marked as -1.
Row 2,Wood lend Tony 2, for Tony, it's +2
Row 3,-3
Row 4, +4
Two problems
Calculate the total net amount of Tony. It should be -1+2-3+4. How should I code in R?
Calculate the total net amount only between Tony and Wood at the point of Tony. Thus Row 4 is unrelated and should be ignored. The trading balance between Tony and Wood is -1+2-3. How to code it?
Note: it's a large data. Map(purrr) is preferred unless you have to use for loop. And the original amounts are all positive. So you have to change it when necessary.