假設你有這個資料框:
> dummy
index ARMA ME
1 4 2,3 -0.00764558073
2 4 3,1 -0.00017109916
3 4 3,2 -0.00038884805
4 4 3,3 -0.00246287881
5 3 1,3 -0.00004263228
6 1 0,1 0.00046965874
7 1 0,2 0.00105372919
8 1 1,0 0.00018798497
9 1 2,1 0.00112475686
10 1 2,2 -0.00121912970
11 1 3,0 0.00181957426
ARMA 列是某種 ID。該資料集按索引從 4 到 1 排列(降序)
我想按索引(降序)排列資料集,首先是最接近 0 的 ME 值
所以這將是所需的輸出:
> dummy
index ARMA ME
1 4 3,1 -0.00017109916
2 4 3,2 -0.00038884805
3 4 3,3 -0.00246287881
4 4 2,3 -0.00764558073
5 3 1,3 -0.00004263228
6 1 1,0 0.00018798497
7 1 0,1 0.00046965874
8 1 0,2 0.00105372919
9 1 2,1 0.00112475686
10 1 2,2 -0.00121912970
11 1 3,0 0.00181957426
提前致謝!!
資料:
> dput(dummy)
structure(list(index = c(4L, 4L, 4L, 4L, 3L, 1L, 1L, 1L, 1L,
1L, 1L), ARMA = c("2,3", "3,1", "3,2", "3,3", "1,3", "0,1", "0,2",
"1,0", "2,1", "2,2", "3,0"), ME = c(-0.00764558072775317, -0.000171099162494111,
-0.000388848046105807, -0.00246287880997775, -0.0000426322805130549,
0.000469658740281779, 0.001053729189345, 0.000187984966060834,
0.00112475685730634, -0.00121912969696577, 0.00181957426209449
)), row.names = c(NA, -11L), class = "data.frame")
uj5u.com熱心網友回復:
dummy[ order(-dummy$index, abs(dummy$ME)), ]
# index ARMA ME
# 2 4 3,1 -0.00017109916
# 3 4 3,2 -0.00038884805
# 4 4 3,3 -0.00246287881
# 1 4 2,3 -0.00764558073
# 5 3 1,3 -0.00004263228
# 8 1 1,0 0.00018798497
# 6 1 0,1 0.00046965874
# 7 1 0,2 0.00105372919
# 9 1 2,1 0.00112475686
# 10 1 2,2 -0.00121912970
# 11 1 3,0 0.00181957426
稍微填寫一下...
如果所有欄位的排序方向(升序或降序)相同,則
order(...)ororder(..., decreasing=TRUE)就足夠了;如果存在混合方向且所有要排序的欄位都是
numericorinteger,則可以否定需要降序排列的欄位并保持其他欄位不變,例如order(asc1, -desc1, -desc3, asc4);如果存在混合方向,則所有其他不是
numeric/integer并且需要減少的欄位order(...)接受一個或多個欄位,并具有可選decreasing=引數,當 時TRUE,將反轉整個排序順序;如果有混合排序(一些升序,一些降序),那么我們可能需要發揮創意;logical欄位總是先排序FALSE,因為 false 實際上是 0,而 true 是 1;如果邏輯欄位排序順序應該顛倒(首先為真),則用否定-或邏輯否定來否定它!,如order(-lgl)ororder(!lgl);數字欄位(字面意思
integer和numeric)可以通過否定它們來單獨反轉,如order(-num);需要反轉的任何其他欄位(包括
character、Date和POSIXt)都需要使用該rank(.)欄位的負數來反轉,例如order(-rank(chr, ties.method="min")).
舉一個更復雜的例子,如果我們有一個帶有欄位num,的資料框char,并且date它們的名稱暗示了這些類,并且我們想要排序:按 num升序,按 char降序,按日期升序,那么我們將使用order(num, -rank(char, ties.method="min"), date).
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/412453.html
標籤:
