Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reorder one row in tibble - move it to the last row

Tags:

r

dplyr

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)
like image 828
SiH Avatar asked Oct 24 '25 19:10

SiH


2 Answers

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
like image 159
jpsmith Avatar answered Oct 27 '25 11:10

jpsmith


tbl |> dplyr::arrange(x == "c")
like image 26
Captain Hat Avatar answered Oct 27 '25 10:10

Captain Hat