我们如何在 R 中的两个表之间执行条件检查

How can we perform condition checking between two tables in R

假设我考虑两个 tables 交易和账户 其中 transaction$account_id 包含 account$account_id

中的因子和唯一值
> transaction
      trans_id account_id amount
             1        100    500
             2        101    200
             3        102    100
             4        100    600
             5        100    700
             6        100    900
             7        101   1000
             8        101  10000
             9        102  20000
            10        101   5000
> account
  account_id Total.amnt notrans transavg
         100       2700       4      675
         101      16200       4     4050
         102      20100       2    10050

现在我的问题是,如何找到 transaction table 中的 amount 是否大于 account table 中的 transavg每个 account_id.

并将其存储在变量中,如果大于 transavg 则因子为 1,如果小于 transavg 则因子为 0。我需要使用什么包。

我们可以用match来比较account_id然后从account中得到对应的amounttable再和[=比较13=] 在 transaction table 中。这将 return 一个布尔值输出,可以使用 as.integer 将其转换为整数。

transaction$flag <- as.integer(transaction$amount > 
          account$transavg[match(transaction$account_id, account$account_id)])

transaction

#   trans_id account_id amount flag
#1         1        100    500    0
#2         2        101    200    0
#3         3        102    100    0
#4         4        100    600    0
#5         5        100    700    1
#6         6        100    900    1
#7         7        101   1000    0
#8         8        101  10000    1
#9         9        102  20000    1
#10       10        101   5000    1

我们可以使用 data.table 的非等连接。将 'data.frame' 转换为 'data.table' (setDT(transaction)),将 'flag' 创建为 0,加入 'amount' on 'account_id' 和 amount > transavg,并将 (:=) 'flag' 赋值为 1.

library(data.table)
setDT(transaction)[, flag := 0][amount, flag := 1, on =.(account_id, amount > transavg)]
transaction
#     trans_id account_id amount flag
# 1:        1        100    500    0
# 2:        2        101    200    0
# 3:        3        102    100    0
# 4:        4        100    600    0
# 5:        5        100    700    1
# 6:        6        100    900    1
# 7:        7        101   1000    0
# 8:        8        101  10000    1
# 9:        9        102  20000    1
#10:       10        101   5000    1