Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201839

Select the last n columns of data frame in R

$
0
0

Is there a way to systematically select the last columns of a data frame? I would like to be able to move the last columns to be the first columns, but maintain the order of the columns when they are moved. I need a way to do this that does not list all the columns using subset(data, select = c(all the columns listed in the new order)) because I will be using many different data frames.

Here's an example where I would like to move the last 2 columns to the front of the data frame. It works, but it's ugly.

A = rep("A", 5)
B = rep("B", 5)
num1 = c(1:5)
num2 = c(36:40)

mydata2 = data.frame(num1, num2, A, B)

# Move A and B to the front of mydata2
mydata2_move = data.frame(A = mydata2$A, B = mydata2$B, mydata2[,1:    (ncol(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

Changing the number of columns in the original data frame causes issues. This works (see below), but the naming gets thrown off. Why do these two examples behave differently? Is there a better way to do this, and to generalize it?

mydata1_move = data.frame(A = mydata1$A, B = mydata1$B, mydata1[,1:   (ncol(mydata1)-2)])

#  A B mydata1...1..ncol.mydata1....2..
#1 A B                                1
#2 A B                                2
#3 A B                                3
#4 A B                                4
#5 A B                                5

Viewing all articles
Browse latest Browse all 201839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>