通过相似的名称重组Dataframe列

时间:2018-09-20 00:27:09

标签: r dataframe dplyr

这是我的数据框:

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

如何更改此数据框列的位置以具有如下输出:

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

有什么帮助吗?

3 个答案:

答案 0 :(得分:1)

长方法是考虑使用starts_with选择助手。您的情况是,您希望将以相同术语(例如“一个”)开头的列和具有相同术语但又带有后缀(“新”)的另一列相邻放置。 starts_with通过捕获名称以相同术语开头的列(例如,以“ one”开头的列包括“ one”和“ one_new”列)并按此顺序排列来实现此目的。

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

答案 1 :(得分:0)

您可以使用所需的列顺序创建新的数据框

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

或使用索引:

df2<-df[c(1,11,2,12,3,13...)] #so on.

答案 2 :(得分:0)

您可以使用以下代码来操纵列名的顺序。

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

或操作列索引

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

或在向量(cols中定义顺序,然后使用lapplygrep检索列名。

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

df[, unlist(lapply(cols, function(x) grep(x, colnames(df), value = TRUE)))]