eyeOfTheStorm
eyeOfTheStorm

Reputation: 351

Sort a tibble by index in R

Looking to sort a tibble by index in R. Any way to do this without using a reverse sequence?

library(tibble)
library(dplyr)

    options(tibble.width = Inf)
    options(dplyr.print_max = Inf) 

Returns the tail for comparison...

iris %>% tail
# Sepal.Length Sepal.Width Petal.Length Petal.Width   Species
# 145          6.7         3.3          5.7         2.5 virginica
# 146          6.7         3.0          5.2         2.3 virginica
# 147          6.3         2.5          5.0         1.9 virginica
# 148          6.5         3.0          5.2         2.0 virginica
# 149          6.2         3.4          5.4         2.3 virginica
# 150          5.9         3.0          5.1         1.8 virginica

(tibbleIris <- as_tibble(iris))

Can sort by reverse sequence, but it's not by index...

tibbleIris[nrow(tibbleIris):1,] # Sorts in reverse order
# # A tibble: 150 × 5
# Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
# <dbl>       <dbl>        <dbl>       <dbl>     <fctr>
#   1            5.9         3.0          5.1         1.8  virginica
# 2            6.2         3.4          5.4         2.3  virginica
# 3            6.5         3.0          5.2         2.0  virginica
# 4            6.3         2.5          5.0         1.9  virginica
# 5            6.7         3.0          5.2         2.3  virginica
# 6            6.7         3.3          5.7         2.5  virginica


tibbleIris %>% arrange(-index)
# Error: object 'index' not found

Upvotes: 0

Views: 9903

Answers (1)

Ben Bolker
Ben Bolker

Reputation: 226732

Still not sure what you mean: this seems to work:

iris %>% as_tibble %>% arrange(desc(as.numeric(rownames(iris))))

(I left out the intermediate assignment to tibbleIris for simplicity). Using rownames is rather un-tidyverse-ish, so I might suggest setting up an explicit index variable instead ...

iris %>% as_tibble %>% mutate(index=seq(n())) %>% 
      arrange(desc(index))

Upvotes: 2

Related Questions