Multiple conditional statement with group_by in R?

Viewed 419

I have a field that I need to run multiple conidtional statements (if/else) based on a group_by function with SERIAL being the group by. I want to create a new field that is added to df with the mutate() function.

Summary of data:

SERIAL INSTALLSITE_CONTRACT_PARTY_NUM INSTALLSITEDUNS_CONTRACT_POD INSTALLSITEPOD_CONTRACT_POD percent_dist
1: ZKZYKBAI                          MATCH                     MISMATCH                       MATCH            0
2: ZLLEJUWA                          MATCH                     MISMATCH                       MATCH            0
3: ZICZVXYG                          MATCH                        MATCH                       MATCH            0
4: ZXQPVFHB                          MATCH                        MATCH                       MATCH            0
5: ZLIUJARF                          MATCH                        MATCH                       MATCH            0
6: ZCUXHMIE                          MATCH                        MATCH                       MATCH            0

I need to write if the matches are equal or not - IF 'INSTALLSITE_CONTRACT_PARTY_NUM' = 'MATCH' & 'INSTALLSITEDUNS_CONTRACT_POD' = 'MATCH' & INSTALLSITEPOD_CONTRACT_POD = 'MATCH' & percent_dist <= 0 THEN 'ACCURATE'...

There are multiple conditions that looks like above but I wanted to get an idea of how I can use this approach in R.

2 Answers

Based on the format of the input data, it seems like a data.table. So, we could use the efficient data.table methods. Specify the columns of interest in .SDcols. Loop over the columns with lapply, create a list of logical vectors and Reduce it to a single logical vector, then add more conditions i.e. with 'percent_dist' and use that in i to change the column 'ACCURATE' to a specified value

library(data.table)
nm1 <- c('INSTALLSITE_CONTRACT_PARTY_NUM', 
        'INSTALLSITEDUNS_CONTRACT_POD',
         'INSTALLSITEPOD_CONTRACT_POD')
i1 <- dt1[, percent_dist <= 0 & Reduce(`&`, 
             lapply(.SD, `==`, 'MATCH')), .SDcols = nm1]
dt1[i1, ACCURATE := val] 
         

You can use dplyr's case_when to handle multiple conditions like so:

dt <- grouped_data %>%
    mutate(
      new_col = case_when(
        INSTALLSITE_CONTRACT_PARTY_NUM == 'MATCH' &
        INSTALLSITEDUNS_CONTRACT_POD == 'MATCH' &
        INSTALLSITEPOD_CONTRACT_POD == 'MATCH' &
        percent_dist <= 0 ~ 'Accurate',
        ...
        other_condition ~ 'result',
        ...
        T ~ 'default result'
      )
    )
Related