H. Yong
H. Yong

Reputation: 171

Order data frame by the last column with dplyr

library(dplyr)
df <- tibble(
  a = rnorm(10),
  b = rnorm(10),
  c = rnorm(10),
  d = rnorm(10)
)

df %>%
  arrange(colnames(df) %>% tail(1) %>% desc())

I am looping over a list of data frames. There are different columns in the data frames and the last column of each may have a different name.

I need to arrange every data frame by its last column. The simple case looks like the above code.

Upvotes: 6

Views: 2149

Answers (3)

shosaco
shosaco

Reputation: 6155

The new dplyr way (I guess from 1.0.0 on) would be using across(last_col()):

library(dplyr)

df <- tibble(
    a = rnorm(10),
    b = rnorm(10),
    c = rnorm(10),
    d = rnorm(10)
)

df %>%
    arrange(across(last_col(), desc))

#> # A tibble: 10 x 4
#>          a       b       c       d
#>      <dbl>   <dbl>   <dbl>   <dbl>
#>  1 -0.283   0.443   1.30    0.910 
#>  2  0.797  -0.0819 -0.936   0.828 
#>  3  0.0717 -0.858  -0.355   0.671 
#>  4 -1.38   -1.08   -0.472   0.426 
#>  5  1.52    1.43   -0.0593  0.249 
#>  6  0.827  -1.28    1.86    0.0824
#>  7 -0.448   0.0558 -1.48   -0.143 
#>  8  0.377  -0.601   0.238  -0.918 
#>  9  0.770   1.93    1.23   -1.43  
#> 10  0.0532 -0.0934 -1.14   -2.08
> packageVersion("dplyr")
#> [1] ‘1.0.4’

Upvotes: 1

Jaap
Jaap

Reputation: 83215

Using arrange_at and ncol:

df %>% arrange_at(ncol(.), desc)

As arrange_at will be depricated in the future, you could also use:

# option 1
df %>% arrange(desc(.[ncol(.)]))

# option 2
df %>% arrange(across(ncol(.), desc))

Upvotes: 11

akrun
akrun

Reputation: 886938

If we need to arrange by the last column name, either use the name string

df %>% 
     arrange_at(vars(last(names(.))), desc)

Or specify the index

df %>%
    arrange_at(ncol(.), desc)

Upvotes: 3

Related Questions