Search code examples
rselect

R - select last 2 columns


I have an dataframe below, in reality it actually has much more columns, and I´d like to select only last two columns.

   df <- read.table(text="
                 date1       date2              date3
    1            NA          2016-12-01    2016-12-01
    2            2017-01-01  2018-10-01    2016-12-01 
    3            2016-12-01  NA            2016-12-01
    4            NA          NA            2016-12-01
", header=TRUE)

How can I do it without specifying column names?

df %>%
  select(date2, date3)

Solution

  • You could use select with tail to get last 2 column names

    library(dplyr)
    
    df %>% select(tail(names(.), 2))
    
    #       date2      date3
    #1 2016-12-01 2016-12-01
    #2 2018-10-01 2016-12-01
    #3       <NA> 2016-12-01
    #4       <NA> 2016-12-01
    

    which in base R is

    df[tail(names(df), 2)]