user6016731
user6016731

Reputation: 382

Sum based on a given criteria

I have the following data set :

Min Max PFQty   SFQty
800 900 0      0
800 900 0   0
800 900 30  30
800 1000    0   0
800 1000    42  42
900 1000    0   0
900 1000    0   0
900 1000    150 150
900 1000    0   0
900 1000    0   0
900 1000    0   0
900 1000    40  40
900 1000    14  14
900 1000    28  28
900 1000    14  14
900 1000    56  56
900 1000    120 120
900 1000    60  60
900 1000    1512    1512
900 1000    1096    1096
900 1100    24  24
1000    1100    9   9
1000    1100    60  60
1000    1100    250 250
1000    1100    435 435

I need to sum columns PFQty only till the difference between columns Min and Max is 100 . If it exceeds 100 then I need to ignore those rows.

Upvotes: 1

Views: 48

Answers (3)

akrun
akrun

Reputation: 886938

Here is an option using data.table

library(data.table)
setDT(df1)[Max  - Min <= 100, .(PFQtySum = sum(PFQty)) , by =  .(Min, Max)]
#    Min  Max PFQtySum
#1:  800  900       30
#2:  900 1000     3090
#3: 1000 1100      754

Upvotes: 1

zx8754
zx8754

Reputation: 56004

Using dplyr, filter, then group by and sum:

library(dplyr)
df1 %>% 
  filter(Max - Min <= 100) %>% 
  group_by(Min, Max) %>% 
  summarise(PFQtySum = sum(PFQty))

#     Min   Max PFQtySum
#   <int> <int>    <int>
# 1   800   900       30
# 2   900  1000     3090
# 3  1000  1100      754

Upvotes: 2

Jan Sila
Jan Sila

Reputation: 1593

I'd create another column

 data$diff<-abs(data$min-data$max)

then it would be easy

sum(data[diff<=100,]$PFQty)

Is it doing what you need?

Upvotes: 0

Related Questions