0
library(tidyverse)
data=tibble(lender=c('Tony','Wood','Tony','Tidy'),borrower=c('Wood','Tony','Wood','Tony'),amount=c(1,2,3,4))

enter image description here

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

  1. Calculate the total net amount of Tony. It should be -1+2-3+4. How should I code in R?

  2. 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.

phiver
  • 23,048
  • 14
  • 44
  • 56
adafdwwf
  • 162
  • 3
  • 12
  • So - what have you done? Does your data look like this with all values positive, or does it include the sign? – bob1 Feb 23 '19 at 03:51
  • The original data has no sign. Those signs are just examples to explain how to calculate the balance. – adafdwwf Feb 23 '19 at 03:55

1 Answers1

2

Here's an approach to the first part that should be pretty fast. By gathering, we get two rows for each loan, one for each role, then we just flip the sign of amount depending on role, and group_by-summarize to get each actor's total net borrowing.

data %>%
  gather(role, name, -amount) %>%
  mutate(net = if_else(role == "borrower",
                       amount,
                       -amount)) %>%
  group_by(name) %>%
  summarize(net = sum(net))

## A tibble: 3 x 2
#  name    net
#  <chr> <dbl>
#1 Tidy     -4
#2 Tony      2
#3 Wood      2

For the second part, I relied on this answer to create an alphabetical pairing of the borrower and lender, and then did the same sort of summing.

data %>%
  rowwise() %>%
  mutate(pair = paste(sort(c(lender, borrower)), collapse = " - "),
         net  = if_else(lender < borrower,
                        amount,
                        -amount)) %>%
  ungroup() %>%
  group_by(pair) %>%
  summarize(net = sum(net))

## A tibble: 2 x 2
#  pair          net
#  <chr>       <dbl>
#1 Tidy - Tony     4
#2 Tony - Wood     2
Jon Spring
  • 55,165
  • 4
  • 35
  • 53