selecting and sorting "numeric columns names", created by a pivot_wider action

Viewed 150

I have a table of data created by pivot_wider. The "names_from" are numbers which are now the column headers in the new table. Would like to select the last column and arrange() descending. The column names (years in this case) may change in number and name depending upon the size of the table being pivoted_wider. I've tried using get() and paste0() to create the column name from the max() value of year, but get an error saying the column doesn't exist.

Code I tried:

        tmp <- pivot_wider(tmp, names_from = YR, values_from = Num_Deals) %>% 
            arrange(ends_with(paste0(max(YRS)))) 
        tmp

Here is the pivot_wider result I would like to sort, by the column with the latest year (2010, in this case):

A tibble: 912 x 7

name 2005 2006 2007 2008 2009 2010
1 Sierra Ventures 5 4 2 2 2 2
2 Mayfield Fund 4 NA 1 NA NA 4
3 Focus Ventures 4 1 2 1 2 NA
1 Answers

There are most likely simpler solutions, but you can use:

library(dplyr)

tmp %>% 
  arrange(desc(!!sym(as.character(max(as.integer(names(.)[grepl("\\d+", names(.))]))))))

This returns

# A tibble: 3 x 7
  name            `2005` `2006` `2007` `2008` `2009` `2010`
  <chr>            <dbl>  <dbl>  <dbl>  <dbl>  <dbl>  <dbl>
1 Mayfield_Fund        4     NA      1     NA     NA      4
2 Sierra_Ventures      5      4      2      2      2      2
3 Focus_Ventures       4      1      2      1      2     NA
Related