although I searched long for solutions, e.g. Assign value to group based on condition in column
I am not able to solve the following problem and would appreciate greatly any help!
I have the following data frame (in reality, many more with thousands of rows):
df <- data.frame(ID1 = c(1,1,1,2,2,2,2,3,3,4,4,4,5,5,5,6,6,6,7,7),
ID2 = c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20),
Percentage = c(0,10,NA,65,79,81,52,0,0,11,12,35,0,24,89,76,0,NA,59,16),
Group_expected_result = c(6,6,6,7,7,7,7,1,1,3,3,3,4,4,4,5,5,5,2,2))
What I want to do is to assign a group type from 1 to 7 to each group as indicated by ID1. Which group type should be assigned is dependent on the conditions of column 3, Percentage (can have values from 0-100) and is split into seven types:
Type 1 has a percentage of 0, i.e.
- Type 1 = 0
- Type 2 > 0 & < 10
- Type 3 > 9 & < 20
- Type 4 > 19 & < 30
- Type 5 > 29 & < 40
- Type 6 > 39 & < 50
- Type 7 > 49
The combination of these types (above) defines the group type (G1-G7) below:
- G1 = only T7
- G2 = only T7 & T2-T6
- G3 = only T2-T6
- G4 = at least one T1, & one T2-T6, & one T7 (= all)
- G5 = only T7 & T1
- G6 = only T2-T6 & T1
- G7 = only T1
The expected result is in the last column of the sample data frame, e.g. the first group consists of types T1 and T2, therefore should be group type G6.
So, the question is how to get the expected result in the last column? I hope I made the problem clear! Thanks in advance!