mardi 12 novembre 2019

Combining ifelse statements and for loops R

I have data on whether someone has been accepted to a range of schools (1 to 35) and how they have preferences these school. My dataset will have many more students and schools eventually but this is a mock-up dataset to do some trail work with. The data looks like this, but will have many more schools also:

> head(Schools)
     ID              S1_AR S1_Rank              S2_AR S2_Rank
1 ID001 Provisional Accept       1 Provisional Accept       2
2 ID002 Provisional Accept       1     No Application      NA
3 ID003 Provisional Reject       1 Provisional Accept       2
4 ID004 Provisional Reject       2 Provisional Accept       1
5 ID005 Provisional Accept       3 Provisional Accept       1

Each person cannot attend more than one school, so if they are provisionally accepted at more than one school their acceptance is dis-considered for the school they have ranked lowest in their preferences. This means that their place can then become available for another student to take.

I've written code which identifies students that have been accepted to schools 1 and 2, compares their ranking, and updates their acceptance status, as below. However, this is for only one pair of schools and I will need to do it for each pair of 35 different schools. Is there a way of using the for loop to automate this process for the different pairs of schools?

Also, I know my code is fairly clunky at the moment but this is the only way I've got it to work at the moment. Would using nested ifelse() help make this code more manageable within a for loop?

Schools$Match <-ifelse(Schools$S1_AR == "Provisional Accept" & Schools$S2_AR == "Provisional Accept", 1, 0)
Schools$Preference<- ifelse(Schools$S1_Rank<Schools$S2_Rank, 1,2)
Schools$S2_AR[Schools$Match == 1 & Schools$Preference == 1]<- "Accepted Elsewhere"
Schools$S1_AR[Schools$Match == 1 & Schools$Preference == 2]<- "Accepted Elsewhere"


head(Schools)

     ID              S1_AR S1_Rank              S2_AR S2_Rank Match Preference
1 ID001 Provisional Accept       1 Accepted Elsewhere       2     1          1
2 ID002 Provisional Accept       1     No Application      NA     0         NA
3 ID003 Provisional Reject       1 Provisional Accept       2     0          1
4 ID004 Provisional Reject       2 Provisional Accept       1     0          2
5 ID005 Accepted Elsewhere       3 Provisional Accept       1     1          2

Aucun commentaire:

Enregistrer un commentaire