【问题标题】:Add column based on other columns values根据其他列值添加列
【发布时间】:2019-04-26 02:17:48
【问题描述】:

老实说,我可以为此想出一个像样的标题。 基本上,我有一个dateframe

ID Qty BasePrice Total
1   2     30      50
1   1     20      20
2   4      5      15

对于每一行我要计算以下内容:

Result = (Qty * BasePrice) - Total

这在 R 中应该很容易做到。但是,我想按 ID 对结果进行分组(求和)。

样本输出:

ID Qty BasePrice Total Results
1   2     30      50     10
1   1     20      20     10
2   4      5      15     5

例如,对于ID=1,值表示((2*30)-50)+((1*20)-20)

关于如何实现这一点的任何想法?

谢谢!

【问题讨论】:

  • 如果您选择每组的总和值,那么library(dplyr);df1 %>% group_by(ID) %>% mutate(Result = sum((Qty * BasePrice) - Total))

标签: r


【解决方案1】:

我们可以做一个group_bysum'Qty'、'BasePrice'和'Total'的乘积之间的差异

library(dplyr)
df1 %>% 
    group_by(ID) %>% 
    mutate(Result = sum((Qty * BasePrice) - Total))
# A tibble: 3 x 5
# Groups:   ID [2]
#     ID   Qty BasePrice Total Result
#  <int> <int>     <int> <int>  <int>
#1     1     2        30    50     10
#2     1     1        20    20     10
#3     2     4         5    15      5

数据

df1 <- structure(list(ID = c(1L, 1L, 2L), Qty = c(2L, 1L, 4L), BasePrice = c(30L, 
 20L, 5L), Total = c(50L, 20L, 15L)), class = "data.frame", row.names = c(NA, 
 -3L))

【讨论】:

  • library(magrittr) 以及管道操作员 (%&gt;%)
  • @NickDylla 当你调用dplyr时,管道将被导出
  • 出于习惯,我仍然打电话给library(magrittr),我认为这对于新的 R 用户来说仍然很有帮助。它提供了一个途径来了解更多关于 dplyr 函数中的管道。
猜你喜欢
  • 1970-01-01
  • 2022-12-17
  • 1970-01-01
  • 2021-07-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多