Diogo Santos
Diogo Santos

Reputation: 830

Add column based on other columns values

I am honest, I could come up with a decent title for this. Basically, I have a dateframe:

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

For each line I want to calculate the following:

Result = (Qty * BasePrice) - Total

Which is supposedly easy to do in R. However, I want to group the results by ID (sum them).

Sample Output:

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

For instance, for ID=1, the values represent ((2*30)-50)+((1*20)-20)

Any idea on how can I achieve this?

Thanks!

Upvotes: 1

Views: 51

Answers (1)

akrun
akrun

Reputation: 887831

We can do a group_by sum of the difference between the product of 'Qty', 'BasePrice' with '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

data

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))

Upvotes: 1

Related Questions