R中的reorder()函數(shù)用于將factor的level快速排序
用法:reorder(x, X, decreasing = FALSE)
- x為原始的vector
- X為期望因子排序的量,長度與x相同幢泼。若為character搀绣,按字母順序排割疾,若為數(shù)字碴犬,按從小到大的順序排
- decreasing參數(shù)與order和sort的decreasing參數(shù)相同蒜焊,默認為F蛉艾,從小到大
- 注:若給第二個參數(shù)前添加負號停做,即
-X
晤愧,也可以達到按相反方向排序的效果
例:
> gene <- c("PSMD1", "GRPEL2", "UCK2", "SEPHS1","UTP11", "KPNA2", "EIF5B", "YARS1")
> coef <- c(0.0058, 0.0117, 0.0135, 0.0065,0.0515, 0.0007, 0.0008, 0.008)
> reorder(gene, coef)
[1] PSMD1 GRPEL2 UCK2 SEPHS1 UTP11 KPNA2 EIF5B YARS1
attr(,"scores")
EIF5B GRPEL2 KPNA2 PSMD1 SEPHS1 UCK2 UTP11 YARS1
0.0008 0.0117 0.0007 0.0058 0.0065 0.0135 0.0515 0.0080
Levels: KPNA2 EIF5B PSMD1 SEPHS1 YARS1 GRPEL2 UCK2 UTP11
可以看到:
- reorder的返回值與原向量相同
- reorder的返回值的因子水平會按照第二個參數(shù)進行排序
- reorder在使用ggplot2進行畫圖時對橫/縱坐標制定順序時非常有用
例:
ggplot(mapping = aes(x = gene, y = coef)) +
geom_bar(stat = "identity")
ggplot(mapping = aes(x = reorder(gene, coef), y = coef)) +
geom_bar(stat = "identity")