Sorry in advanced for the bad title, but I really didn't know how to word it succinctly.
I have a dataframe I'm playing around with where an item can be in any of 4 categories, not limited to 1. Here's an example of the dummy matrix I'm working with:
ID <- 1:7
A <- c(1,0,0,1,1,0,0)
B <- c(0,1,0,0,1,0,1)
C <- c(0,0,0,0,0,1,1)
D <- c(1,0,1,1,0,0,0)
A_B <- (A+B > 0)*1
C_D <- (C+D > 0)*1
Cost <- c(25, 52, 11, 75, 45, 5, 34)
df <- data.frame(ID, A, B, C, D, A_B, C_D, A_B_C_D = 1, Cost)
df
ID A B C D A_B C_D A_B_C_D Cost
1 1 0 0 1 1 1 1 25
2 0 1 0 0 1 0 1 52
3 0 0 0 1 0 1 1 11
4 1 0 0 1 1 1 1 75
5 1 1 0 0 1 0 1 45
6 0 0 1 0 0 1 1 5
7 0 1 1 0 1 1 1 34
I need for this data frame to be organized such that row 1 contains an A, row 2 a B, row 3 a C, row 4 a D, row 5 an A or B, row 6 a C or D, and row 7 whatever is left over. I can't use arrange
since starting with desc(A)
would automatically give 1, 4, 5. An acceptable solution to this problem would be:
Order <- c(4, 2, 7, 1, 5, 3, 6)
df[Order,]
df
ID A B C D A_B C_D A_B_C_D Cost
4 1 0 0 1 1 1 1 75
2 0 1 0 0 1 0 1 52
7 0 1 1 0 1 1 1 34
1 1 0 0 1 1 1 1 25
5 1 1 0 0 1 0 1 45
3 0 0 0 1 0 1 1 11
6 0 0 1 0 0 1 1 5
Essentially, the diagonal needs to be 7 straight ones, but I can't think of how to program it to sort correctly no matter the data set. I feel like this should be really easy but I'm just not seeing it. Would transposing make it easier?
Thanks in advance.