Home > Software design >  Reorder one row in tibble - move it to the last row
Reorder one row in tibble - move it to the last row

Time:05-28

How do I rearrange the rows in tibble?

I wish to reorder rows such that: row with x = "c" goes to the bottom of the tibble, everything else remains same.

library(dplyr)

tbl <- tibble(x = c("a", "b", "c", "d", "e", "f", "g", "h"),
              y = 1:8)

CodePudding user response:

An alternative to dplyr::arrange(), using base R:

tbl[order(tbl$x == "c"), ] # Thanks to Merijn van Tilborg

Output:

#   x         y
#   <chr> <int>
# 1 a         1
# 2 b         2
# 3 d         4
# 4 e         5
# 5 f         6
# 6 g         7
# 7 h         8
# 8 c         3

CodePudding user response:

tbl |> dplyr::arrange(x == "c")

CodePudding user response:

Using forcats, convert to factor having c the last, then arrange. This doesn't change the class of the column x.

library(forcats)

tbl %>% 
  arrange(fct_relevel(x, "c", after = Inf))
  
# # A tibble: 8 x 2
#   x         y
#   <chr> <int>
# 1 a         1
# 2 b         2
# 3 d         4
# 4 e         5
# 5 f         6
# 6 g         7
# 7 h         8
# 8 c         3

If the order of x is important, it is better to keep it as factor class, below will change the class from character to factor with c being last:

tbl %>% 
  mutate(x = fct_relevel(x, "c", after = Inf)) %>% 
  arrange(x)
  • Related