[英]Reorganizing Dataframe columns by similar names
這是我的數據框:
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
有什么幫助嗎?
一種長方法是考慮使用starts_with
select助手。 您的情況是,您希望以相同術語(例如,“一個”)開頭的列和具有相同術語但又帶有后綴(“新”)的另一列彼此相鄰放置。 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"))
您可以使用所需的列順序創建一個新的數據框
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.
您可以使用以下代碼來操縱列名的順序。
df[, as.vector(t(matrix(colnames(df), ncol = 2)))]
或操縱列索引
df[, as.vector(t(matrix(1:20, ncol = 2)))]
或在向量中定義順序( cols
),然后使用lapply
和grep
檢索列名。
cols <- c("one","two","three","four","five","six","seven","eight","nine","ten")
df[, unlist(lapply(cols, function(x) grep(x, colnames(df), value = TRUE)))]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.