6
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.

Henrik
  • 65,555
  • 14
  • 143
  • 159
H. Yong
  • 151
  • 11

3 Answers3

11

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))
Jaap
  • 81,064
  • 34
  • 182
  • 193
  • `arrange_at` is deprecated as of dplyr 0.7.0. What is a viable alternative now? – Wojciech Kulma Aug 31 '20 at 08:59
  • 1
    @wklm `arrange_at` is still part of [tag:dplyr] and also still works; it has the label *superseded* though, which means it is not under active development and a candidate for deprication; anyway, updated the answer – Jaap Sep 01 '20 at 11:53
  • 1
    thanks! Alternatively this works too: ```df %>% arrange(desc(tail(colnames(.), 1)))``` – Wojciech Kulma Sep 01 '20 at 12:59
3

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)
akrun
  • 874,273
  • 37
  • 540
  • 662
1

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’
shosaco
  • 5,915
  • 1
  • 30
  • 48