case when for multiple conditions not working in R

Viewed 47

Here's my code:

    breakover <- function(correlation, growth_factor, wells_per_section, max_breakover = 16){
           case_when(correlation[wells_per_section == max_breakover] > 0.999 ~ max_breakover,
                all(growth_factor) > 0.8 ~ max_breakover,
                T ~ wells_per_section[min(which(growth_factor < 0.8))]-1)
    }
  

If the 16th correlation between section_eur and wells_per_section is greater than 0.999, record the breakover spacing as 16.

If the growth_factor column is always > 0.8 (from first row to the max row for the same reservoir_id), record the breakover spacing as 16,

The third condition is if none of the above is true, go find where growth_factor is <0.8 locate the cell above it since that's the last >0.8 value, and record the wells_per_section, so when I don't have "all(growth_factor) > 0.8 ~ max_breakover," it's working fine, when I add it, it's not working as desired, but I do need that condition.

And here's the partial dataset if it helps to understand my problem:

data <- tibble::tribble(
  ~reservoir_id, ~Wells_per_section,        ~well_eur,     ~section_eur,         ~incr_eur,      ~growth_factor,      ~correlation,
            187,                 1L, 23175.4846595876, 23175.4846595876,  23175.4846595876,                   1,                 1,
     

I'll then apply this function to get a new data frame:

breakover_spacing <- sim_breakover %>%
  dplyr::group_by(reservoir_id)%>%
  dplyr::summarise(breakover = breakover(correlation, growth_factor, Wells_per_section))

This would be the output:

  reservoir_id, breakover
       187         16
       188          2
    

I think my issue is in the case when "all(growth_factor) > 0.8 ~ max_breakover"

1 Answers

There are couple of issues in the breakover code i.e. all(growth_factor) > 0.8 would be all(growth_factor > 0.8) (as all(growth_factor) returns TRUE when all the values are not 0 instead it should be based on the logical condition with 0.8) and in the first condition should be wrapped in any. Also, as this is a summarisation which involves returning a single value, we may use if/else here

library(dplyr)
sim_breakover %>%
  group_by(reservoir_id) %>% 
  dplyr::summarise(breakover =  if(any(correlation > 0.999 & 
      Wells_per_section == 16) |all(growth_factor > 0.8)) 16 
     else first(Wells_per_section[growth_factor < 0.8])-1)

-output

# A tibble: 2 × 2
  reservoir_id breakover
         <dbl>     <dbl>
1          187        16
2          188         2
Related