Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to arrange by the last colname 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.

like image 723
H. Yong Avatar asked Dec 14 '22 21:12

H. Yong


2 Answers

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))
like image 168
Jaap Avatar answered Dec 16 '22 12:12

Jaap


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)
like image 27
akrun Avatar answered Dec 16 '22 11:12

akrun