Select the last n columns of data frame in R

The problem described doesn't match the title, and existing answers address the moving columns part, doesn't really explain how to select last N columns.

If you wanted to just select the last column in a matrix/data frame without knowing the column name:

mydata2[,ncol(mydata2)]

and if you want last n columns, try

mydata[,(ncol(mydata2)-n-1):ncol(mydata2)]

A little cumbersome, but works. Could write wrapper function if you plan to use it regularly.


You could use something like this:

move_to_start <- function(x, to_move) {
  x[, c(to_move, setdiff(colnames(x), to_move))]
} 

move_to_start(mydata2, c('A', 'B'))

#   A B num1 num2
# 1 A B    1   36
# 2 A B    2   37
# 3 A B    3   38
# 4 A B    4   39
# 5 A B    5   40

Alternatively, if you want to move the last n columns to the start:

move_to_start <- function(x, n) {
  x[, c(tail(seq_len(ncol(x)), n), seq_len(ncol(x) - n))]
} 

move_to_start(mydata2, 2)

#   A B num1 num2
# 1 A B    1   36
# 2 A B    2   37
# 3 A B    3   38
# 4 A B    4   39
# 5 A B    5   40