Mel
Mel

Reputation: 520

How to use the dplyr package and the arrange command to sort rows by specific order in R

I want to know to use the dplyr package and the arrange command to sort rows by specific order in R.

Here is my dataset:

example_data <- 
  data.frame(
    row__name = c("IV_1", "IV_2", "DV_4", "Intercept"),
    row__type = c("IV", "IV", "DV", "model"),
    score = c("10", "15", "20", "25")
  )

> example_data
  row__name row__type score
1      IV_1        IV    10
2      IV_2        IV    15
3      DV_4        DV    20
4 Intercept     model    25

I want to arrange the data in 2 ways using code:

  1. Rows are ordered from top to bottom with row__type == "model" first, then "IV", then "DV", with normal alphanumeric order within the smallest levels.
  2. Rows are ordered from top to bottom with row__type == "model" first, then "DV", then "IV", with reverse alphanumeric order within the smallest levels.

Product 1 would look like this:

example_data__Product_1 <- 
  data.frame(
    row__name = c("Intercept", "IV_1", "IV_2", "DV_4"),
    row__type = c("model", "IV", "IV", "DV"),
    score = c("25", "10", "15", "20")
  )

> example_data__Product_1
  row__name row__type score
1 Intercept     model    25
2      IV_1        IV    10
3      IV_2        IV    15
4      DV_4        DV    20

Product 2 would look like this:

example_data__Product_2 <- 
  data.frame(
    row__name = c("Intercept", "DV_4", "IV_2", "IV_1"),
    row__type = c("model", "DV", "IV", "IV"),
    score = c("25", "20", "15", "10")
  )

> example_data__Product_2
  row__name row__type score
1 Intercept     model    25
2      DV_4        DV    20
3      IV_2        IV    15
4      IV_1        IV    10

Is this possible? If so, how would I complete this task?

Thanks ahead of time.

Upvotes: 1

Views: 527

Answers (1)

Simon.S.A.
Simon.S.A.

Reputation: 6941

Because arrange is primarily alphabetic or numeric sorting, I would implement custom order/sorting using an additional sorter column:

example_data %>%
  mutate(custom_order = case_when(row_type == "model" ~ 1,
                                  row_type == "IV" ~ 2,
                                  row_type == "DV" ~ 3)) %>%
  arrange(custom_order, row_name) %>%
  select(row_name, row_type, score)

This will produce example_data__Product_1 that you requested.

Upvotes: 2

Related Questions