I have a dataset with 500 observations. Two of the variables are "test" which is a continuous variable of a test score and "classroom" which is a numerical variable indicating which classroom (1-20) the observation is nested in. I want to create a new variable "TX" where the four observations with the lowest "test" score from each classroom is a 1 and every other observation is a 0. With a sample of 500 evenly distributed across 20 classrooms, the TX variable should contain 80 1's and 420 0's.
This helps me locate/subset the lowest 4 in each classroom, but I want to mutate my original data set to add a TX column on the end of it where all of these observations would have a 1 and everyone else gets a 0.
data_new1 <- data[order(data$test1, decreasing = FALSE), ]
data_new1 <- Reduce(rbind,
by(data_new1,
data_new1["classroom"],
head,
n = 4))