【问题标题】:How to collect unique values, and sum across other columns with conditions如何收集唯一值,并在具有条件的其他列中求和
【发布时间】:2021-05-19 09:55:48
【问题描述】:

我有很多大约一百万行的金融交易数据,我希望能够将这些数据压缩成一个包含唯一用户 ID 列表的新数据框。然后,我希望能够在某些条件下为他们的帐户添加“交易”,即如果 TransactionTypeId == 2 & AC_Type== 19。我会为此在 excel 中使用 sumifs,但文件的大小意味着它几乎不可能在我的电脑上运行。

df<- structure(list(UserId = c(1, 1, 1, 1, 2, 
2, 2, 3, 3, 3, 4, 5, 6, 
6, 6, 7, 7, 7, 8, 8, 8, 
8, 8, 9, 9, 9, 10, 11, 12, 
12, 13, 13, 13, 14, 14, 15, 15, 
16, 16, 16), TransactionTypeId = c(14, 1, 1, 70, 
15, 1, 1, 14, 1, 1, 70, 14, 14, 1, 1, 14, 1, 1, 14, 1, 1, 1, 
1, 14, 1, 1, 14, 14, 1, 1, 14, 1, 1, 1, 1, 70, 70, 14, 1, 1), 
    AC_Type = c(21, 21, 21, 21, 19, 19, 19, 19, 19, 19, 19, 19, 
    19, 19, 19, 21, 21, 21, 19, 19, 19, 19, 19, 19, 19, 19, 20, 
    19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20), Trades = c(30, 
    30, 0.00067116, 0.00067115, 249, 249, 0.00533033, 48.75, 
    48.75, 0.00101298, 0.00533, 24.37, 146.25, 146.25, 0.00309109, 
    100.01, 100.01, 0.00233551, 97.5, 90, 0.00189134, 5, 0.00245851, 
    234, 234, 0.00500802, 100.01, 48.75, 48.5, 0.0275474, 24, 
    24, 0.00051975, 100, 0.00223998, 0.00051975, 0.00205, 9.75, 
    8.75, 0.00017811)), row.names = c(NA, -40L), class = c("tbl_df", 
"tbl", "data.frame"))

【问题讨论】:

  • 到目前为止你尝试过什么?目前尚不清楚您是尝试添加这些特定条件,还是更广泛的摘要集或其他内容

标签: r unique


【解决方案1】:

你可以取sum你要计算的逻辑条件。

library(dplyr)

df %>%
  group_by(UserId) %>%
  summarise(count = sum(Trades[TransactionTypeId == 2 & AC_Type== 19]))

【讨论】:

  • 嗨 - 使用它时,它会为每个用户 ID 计算有多少交易是 TransactionTypeId == 2 & AC_Type ==19 但我想总结交易量,例如,对于用户 1,如果条件是 TransactionTypeId == 1 & AC_Type ==21,我希望返回 30.00006,而不是 2。
【解决方案2】:

不太清楚你想要什么......

libary(dplyr)
df %>%
  group_by(UserId) %>%
  filter(TransactionTypeId == 1 & AC_Type == 19) %>%
  summarise(sum = sum(Trades))
# A tibble: 6 x 2
  UserId   sum
   <dbl> <dbl>
1      2 249. 
2      3  48.8
3      6 146. 
4      8  95.0
5      9 234. 
6     12  48.5

这里首先是group_byUserId,然后是filter那些符合您条件的行(注意:我已将2更改为1,因为样本中没有任何2s数据),最后是summarise,将Trades中的值相加。

【讨论】:

  • 谢谢 - 这正是我想要的
【解决方案3】:

使用data.table

library(data.table)
setDT(df)[, .(count = sum(Trades[TransactionTypeId == 2 & 
     AC_Type== 19], na.rm = TRUE)), UserId]

【讨论】:

    猜你喜欢
    • 2013-03-12
    • 1970-01-01
    • 2019-10-03
    • 2018-05-04
    • 2020-11-15
    • 1970-01-01
    • 2020-05-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多