How to reduce and automate my code

To categorized my data, I use a procedure mutate(case_when()). But my condition are reptitive and I wonder if it's possible to insert a loop in it. Indeed my number of test is variable and I don't want to have to modify my code if I have more or less test. I made a variable to stock the number test, named maxTest.

This is an example to illustrate my though, here maxTest = 3 :

commun<-commun %>% 
  mutate(Class = case_when(
    resultatD1 == 'I' & diff_d1>0 & diff_d1<=24 ~ "A",
    resultatD2 == 'I' & diff_d2>0 & diff_d2<=24 ~ "A",
    resultatD3 == 'I' & diff_d3>0 & diff_d3<=24 ~ "A",
    resultatD1 == 'N' & diff_d1>0 & diff_d1<=24 ~ "B",
    resultatD2 == 'N' & diff_d2>0 & diff_d2<=24 ~ "B",
    resultatD3 == 'N' & diff_d3>0 & diff_d3<=24 ~ "B",
    resultatD1 == 'P' & resul_D1 == 0 & diff_d1>0 & diff_d1<=24 ~ "C",
    resultatD2 == 'P' & resul_D2 == 0 & diff_d2>0 & diff_d2<=24 ~ "C",
    resultatD3 == 'P' & resul_D3 == 0 & diff_d3>0 & diff_d3<=24 ~ "C",
    resultatD1 == 'P' & resul_D1 == 0 & diff_d1> 24 & diff_d1<=60 ~ "D",
    resultatD2 == 'P' & resul_D2 == 0 & diff_d2> 24 & diff_d2<=60 ~ "D",
    resultatD3 == 'P' & resul_D3 == 0 & diff_d3> 24 & diff_d3<=60 ~ "D")

And I want to do something like this, depending on maxTest :

commun<-commun %>% 
  mutate(for (i in 1:maxTest)(Class = case_when(
    resultatDi == 'I' & diff_di>0 & diff_di<=24 ~ "A",

    resultatDi == 'N' & diff_di>0 & diff_di<=24 ~ "B",

    resultatDi == 'P' & resul_Di == 0 & diff_d1>0 & diff_di<=24 ~ "C",

    resultatDi == 'P' & resul_Di == 0 & diff_d1> 24 & diff_di<=60 ~ "D")

or

commun<-commun %>% 
  mutate(Class = case_when(
    for (i in 1:maxTest) resultatDi == 'I' & diff_di>0 & diff_di<=24 ~ "A",

    for (i in 1:maxTest) resultatDi == 'N' & diff_di>0 & diff_di<=24 ~ "B",

    for (i in 1:maxTest) resultatDi == 'P' & resul_Di == 0 & diff_d1>0 & diff_di<=24 ~ "C",

    for (i in 1:maxTest) resultatDi == 'P' & resul_Di == 0 & diff_d1> 24 & diff_di<=60 ~ "D")

To give my data in example, it's like this :
id / name / resultatD1/resul_d1/diff_d1/ resultatD2/resul_d2/diff_d2/resultatD3/resul_d3/diff_d3/ Class
06/james/P/0/12/ / / / / / /C
14/franck/N/0/22/I/0/4/I/3/7/A
42/smith/N/0/15/P/0/40/ / / /D

I have no idea of if this is possible or what to do to have this result.

Thank you for your time.

A post was merged into an existing topic: Insert loop into a case_when()

Please do not duplicate open topics