0

this is my dataframe:

df<-as.data.frame(matrix(rexp(200, rate=.1), ncol=20))
colnames(df)<-c("one","two","three","four","five","six","seven","eight","nine","ten","one_new","two_new","three_new","four_new","five_new","six_new","seven_new","eight_new","nine_new","ten_new")

How can I change the positions of this dataframe columns to have an output like this:

One | One_new | two | two_new | three | three_new|.....|ten | ten_new

any help?

www
  • 38,575
  • 12
  • 48
  • 84
Laura
  • 675
  • 10
  • 32
  • please refer to this SO question - https://stackoverflow.com/questions/5620885/how-does-one-reorder-columns-in-a-data-frame – Suhas Hegde Sep 20 '18 at 00:32

3 Answers3

1

A long approach would be to consider using the starts_with select helpers. Your situation is that you want the columns who start with the same term (e.g. "one") and another column with the same term but with an additional suffix ("new") to be placed next to one another. starts_with does this by capturing columns whose names begin with the same term (e.g. starts with "one" includes both columns "one" and "one_new") and arranging it in that order.

df2 <- df %>%
  select(starts_with("one"), starts_with("two"), starts_with("three"), starts_with("four"),
     starts_with("five"), starts_with("six"), starts_with("seven"), starts_with("eight"),
     starts_with("nine"), starts_with("ten"))
DTYK
  • 1,098
  • 1
  • 8
  • 33
0

You can create a new dataframe with the order of columns you want

df2<-df[c("one","One_new","two","two_new","three","three_new","ten","ten_new")]

or by using indexes:

df2<-df[c(1,11,2,12,3,13...)] #so on.
Sumanth Rao
  • 368
  • 1
  • 7
0

You can use the following code to manipulate the order of the column names.

df[, as.vector(t(matrix(colnames(df), ncol = 2)))]

Or manipulate the column index

df[, as.vector(t(matrix(1:20, ncol = 2)))]

Or define the order in a vector (cols), and then use lapply and grep to retrieve the column names.

cols <- c("one","two","three","four","five","six","seven","eight","nine","ten")

df[, unlist(lapply(cols, function(x) grep(x, colnames(df), value = TRUE)))]
www
  • 38,575
  • 12
  • 48
  • 84