简体   繁体   中英

Reorganizing Dataframe columns by similar names

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?

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 (eg "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 (eg 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"))

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.

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)))]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM