A collection of only rows based on the values ​​of other columns

I have this dataset

  CASHPOINT_ID         DT     status   QT_REC
1   N053360330 2016-01-01 end_of_day      5
2   N053360330 2016-01-01 end_of_day      2
3   N053360330 2016-01-02 before          9
4   N053360330 2016-01-02 before         NA
5   N053360330 2016-01-03 end_of_day     16
6   N053360330 2016-01-03 end_of_day     NA

I want to aggregate only rows that do not have the status of the column marked as “before” and do not leave others untouched. The resulting dataset should look like

 CASHPOINT_ID         DT     status       QT_REC
    1   N053360330 2016-01-01 end_of_day      7
    3   N053360330 2016-01-02 before          9
    4   N053360330 2016-01-02 before         NA
    5   N053360330 2016-01-03 end_of_day     16

Thank.

+4
source share
3 answers

Using data.table

Assuming your source data is called dtand was setDT(), then you could do:

df <- rbind(
  dt[status == "end_of_day", .(QT_REC = sum(QT_REC, na.rm = TRUE)), 
     by = .(CASHPOINT_ID, DT, status)],
  dt[status != "end_of_day"]
)[order(DT)]

print(df)
   CASHPOINT_ID         DT     status QT_REC
1:   N053360330 2016-01-01 end_of_day      7
2:   N053360330 2016-01-02     before      9
3:   N053360330 2016-01-02     before     NA
4:   N053360330 2016-01-03 end_of_day     16
+2
source

This is a solution using dplyr.

    library(dplyr)
    df %>%  
          group_by(floor_date(DT, "day"),status) %>% 
          summarise(QT_REC = sum(QT_REC, na.rm = T))
0
source

Another solution plyr:

ddply(.data = df,.variables = c('CASHPOINT_ID','DT','status'),
function(t){
    if(t$status[1]!='before'){
        unique(mutate(t,QT_REC=sum(QT_REC,na.rm=TRUE)))
    }else{
        t
    }
})

#  CASHPOINT_ID          DT     status QT_REC
#1   N053360330  2016-01-01 end_of_day      7
#2   N053360330  2016-01-02     before      9
#3   N053360330  2016-01-02     before     NA
#4   N053360330  2016-01-03 end_of_day     16
0
source

Source: https://habr.com/ru/post/1692356/


All Articles