标题是不言自明的,我知道如何根据列对数据框进行排序,我知道如何对变量进行自然排序,但我不能使用自然排序对数据框进行排序。
检查以下MWE:
mydf <- data.frame(name=c("B","C","A","E","F","Z","U","D","G","J"),
section=c(NA,"section1","section2","section2","section10","section1",
NA,"section10","section3",NA))
mydf <- mydf[order(mydf$section, mydf$name, decreasing=FALSE),]#normal sort on data frame
library(gtools)
sortvar <- mixedsort(mydf$section)#natural sort on variable
sortvar
#NATURAL SORT ON DATAFRAME???
我希望获得一个数据框,首先按&#34;部分&#34;,然后按&#34; name&#34;,使用自然排序,如下:
name section
2 C section1
6 Z section1
3 A section2
4 E section2
9 G section3
8 D section10
5 F section10
1 B <NA>
10 J <NA>
7 U <NA>
任何人?谢谢!
答案 0 :(得分:2)
mydf[with(mydf, order(as.integer(sub('\\D+', '', section)), name)),]
# name section
#2 C section1
#6 Z section1
#3 A section2
#4 E section2
#9 G section3
#8 D section10
#5 F section10
#1 B <NA>
#10 J <NA>
#7 U <NA>