根据其他列值添加列

时间:2019-04-25 18:12:34

标签: r

老实说,我可以为此拿出一个体面的头衔。 基本上,我有一个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)

关于如何实现此目标的任何想法?

谢谢!

1 个答案:

答案 0 :(得分:1)

我们可以对“数量”,“基本价格”与“总计”乘积之间的差异进行group_by sum

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))
相关问题