如何检查数据框中的双向关系?

Sha*_*ron 2 r

如果我有一个像这样的格式的数据框

mydata <- data.frame(donor = c("Person A", "Person A", "Person A", "Person B", 
      "Person B", "Person C"), recipient = c("Person B", "Person C", "Person F", 
       "Person A", "Person C", "Person B"), Total = c(30, 40, 12, 75, 80, 20), stringsAsFactors = FALSE)
Run Code Online (Sandbox Code Playgroud)

我想找出每对之间的净捐款,有效的方法(或任何方式),以确定是否有人A作为捐赠者,B人作为接受者,B人作为捐赠者和人A作为收件人那么找到他们之间的网?

换句话说,如果A人向C人捐40,但C人没有给A任何东西,那么从A到C的净捐赠是40(从C到A是-40); 但如果A捐赠了30到B和B捐赠了75到A,那么从A到B的净捐赠是-45而B到A是+45.

mle*_*gge 5

您可以使用合并:

> res <- merge(mydata, mydata, by.x = c("donor", "recipient"), by.y = c("recipient", "donor"), suffixes = c(".donor", ".recipient"), all.x = TRUE)
> res$Net <- with(res, ifelse(is.na(Total.recipient), Total.donor, Total.donor - Total.recipient))
> res
     donor recipient Total.donor Total.recipient Net
1 Person A  Person B          30              75 -45
2 Person A  Person C          40              NA  40
3 Person A  Person F          12              NA  12
4 Person B  Person A          75              30  45
5 Person B  Person C          80              20  60
6 Person C  Person B          20              80 -60
Run Code Online (Sandbox Code Playgroud)