如何按自然排序重新排列R数据框的混合字符数字列?
正确对R数据框列进行自然排序的方法
先看原始数据框:
table <- data.frame( C1 = c(1,0,0), C10 = c(1,0,0), C11 = c(1,0,0), C12 = c(1,0,0), C13 = c(0,0,0), C14 = c(0,0,0), C15 = c(0,0,0), C16 = c(0,0,0), C17 = c(0,0,0), C18 = c(0,0,0), C2 = c(0,0,0), C3 = c(0,0,0), C4 = c(0,1,0), C5 = c(0,0,0), C6 = c(0,0,0), C7 = c(0,0,0), C8 = c(0,0,0), C9 = c(0,0,0), row.names = c("Mest", "Dlk1", "Meg3") )
你之前的操作只修改了列名的字符串顺序,没有调整数据框的列位置,导致列名和对应数据错位:
colnames(table) <- stringr::str_sort(colnames(table), numeric = TRUE)
要实现列的自然排序,核心是先获取排序后的列名向量,再用这个向量重新索引数据框,让列名和数据同步调整:
方案1:使用stringr包实现
library(stringr) # 生成自然排序后的列名列表 sorted_col_names <- str_sort(colnames(table), numeric = TRUE) # 用排序后的列名重新索引数据框,完成排序 table_sorted <- table[, sorted_col_names]
排序后的数据框如下:
table_sorted #> C1 C2 C3 C4 C5 C6 C7 C8 C9 C10 C11 C12 C13 C14 C15 C16 C17 C18 #> Mest 1 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 #> Dlk1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 #> Meg3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
方案2:不依赖第三方包(base R实现)
如果不想加载额外包,可以手动提取列名中的数字部分排序:
# 提取列名中的数字并转为整数 col_numbers <- as.integer(sub("C", "", colnames(table))) # 根据数字排序得到列名顺序 sorted_col_names <- colnames(table)[order(col_numbers)] # 重新索引数据框 table_sorted <- table[, sorted_col_names]
或者使用gtools包的mixedsort函数:
library(gtools) table_sorted <- table[, mixedsort(colnames(table))]
内容的提问来源于stack exchange,提问作者jonny jeep
相关产品推荐
相关产品推荐

