How would I go about conditionally reorganizing this data frame? I want for each of my groups of ourid, the us values to be at the top followed by each the same comp and their products sold (see second table). Currently, it lists all tape products then all glue products. I’d like it to look like the second table though where it switches off and the same compid are by each other.
So, basically I want to just reorganize the values with a class of comp and keep us at the top for each of our groups.
| ourid | class | compid | Product |
|---|---|---|---|
| 1 | us | NA | Tape |
| 1 | us | NA | Glue |
| 1 | comp | 101 | Tape |
| 1 | comp | 102 | Tape |
| 1 | comp | 103 | Tape |
| 1 | comp | 101 | Glue |
| 1 | comp | 102 | Glue |
| 1 | comp | 103 | Glue |
| 2 | us | NA | Tape |
| 2 | us | NA | Glue |
| 2 | comp | 201 | Tape |
| 2 | comp | 202 | Tape |
| 2 | comp | 203 | Tape |
| 2 | comp | 201 | Glue |
| 2 | comp | 202 | Glue |
| 2 | comp | 203 | Glue |
| ourid | class | compid | Product |
|---|---|---|---|
| 1 | us | NA | Tape |
| 1 | us | NA | Glue |
| 1 | comp | 101 | Tape |
| 1 | comp | 101 | Glue |
| 1 | comp | 102 | Tape |
| 1 | comp | 102 | Glue |
| 1 | comp | 103 | Tape |
| 1 | comp | 103 | Glue |
| 2 | us | NA | Tape |
| 2 | us | NA | Glue |
| 2 | comp | 201 | Tape |
| 2 | comp | 201 | Glue |
| 2 | comp | 202 | Tape |
| 2 | comp | 202 | Glue |
| 2 | comp | 203 | Tape |
| 2 | comp | 203 | Glue |
This code gets kind of close – Tape and Glue to switch between each other – but doesn’t organize it by IDs how I need.
data2 <-
data %>%
group_by(ourid) %>%
arrange(compid)
>Solution :
It looks like you want to arrange the data first by ourid, then by class (descending), then by compid, then by product (descending). We’re using descending for class and product because your desired order seems to be reverse alphabetical. If you have more than 2 categories of product or class, you could do a custom order by converting them to factor class and specifying the order of the levels.
data %>% arrange(ourid, desc(class), compid, desc(product))