我有以下数据框:
tdf <- structure(list(GO = c("Cytokine-cytokine receptor interaction",
"Cytokine-cytokine receptor interaction|Endocytosis", "I-kappaB kinase/NF-kappaB signaling",
"NF-kappa B signaling pathway", "NF-kappaB import into nucleus",
"T cell chemotaxis"), PosCount = c(17, 18, 4, 5, 1, 2), shortgo = structure(c(1L,
1L, 2L, 2L, 2L, 3L), .Label = c("z", "X", "y"), class = "factor")), .Names = c("GO",
"PosCount", "shortgo"), row.names = c(NA, 6L), class = "data.frame")
看起来像这样:
GO PosCount shortgo
1 Cytokine-cytokine receptor interaction 17 z
2 Cytokine-cytokine receptor interaction|Endocytosis 18 z
3 I-kappaB kinase/NF-kappaB signaling 4 X
4 NF-kappa B signaling pathway 5 X
5 NF-kappaB import into nucleus 1 X
6 T cell chemotaxis 2 y
然后,我要做的是先按字母顺序按
shortgo
排序(不区分大小写),然后对每个shortgo
组内部按PosCount
排序。产生此: GO PosCount shortgo
NF-kappa B signaling pathway 5 X
I-kappaB kinase/NF-kappaB signaling 4 X
NF-kappaB import into nucleus 1 X
T cell chemotaxis 2 y
Cytokine-cytokine receptor interaction|Endocytosis 18 z
Cytokine-cytokine receptor interaction 17 z
但是为什么这不起作用:
library(dplyr)
tdf[order(tdf$shortgo),]
tdf <- tdf %>% group_by(shortgo) %>% arrange(desc(PosCount))
什么是正确的方法?
最佳答案
您所需要做的就是将它们组合成一个呼叫。虽然您需要先将shortgo
转换为character
类(请参见下面的说明)
tdf %>%
arrange(as.character(shortgo), desc(PosCount))
# GO PosCount shortgo
# 1 NF-kappa B signaling pathway 5 x
# 2 I-kappaB kinase/NF-kappaB signaling 4 x
# 3 NF-kappaB import into nucleus 1 x
# 4 T cell chemotaxis 2 y
# 5 Cytokine-cytokine receptor interaction|Endocytosis 18 z
# 6 Cytokine-cytokine receptor interaction 17 z
因此,您需要转换为字符的原因是因为
shortgo
是一个基本上是具有integer
属性的levels
向量的因素。因此,order
使用这些整数来对向量进行排序。在您的情况下,整数与级别的正确顺序不符tdf$shortgo
## [1] z z x x x y
## Levels: z x y
as.numeric(tdf$shortgo)
## [1] 1 1 2 2 2 3
因此,您可以看到
z
编码为1,x
编码为2,而y
编码为3,而应为3、2、1。因此,sort
返回“错误”结果sort(tdf$shortgo)
# 1] z z x x x y
# Levels: z x y
相比于
test <- factor(sort(as.character(tdf$shortgo)))
sort(test)
## [1] x x x y z z
## Levels: x y z