拆分数据框并根据特定列对拆分值进行排序

时间:2015-04-28 07:29:14

标签: r dataframe

我有以下数据框

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(7L, 
7L, 18L, 18L, 18L, 21L), .Label = c("TNF", "adaptive", "alpha", 
"apop", "beta", "chemokine", "cytokine", "death", "defense", 
"gamma", "immune response", "infla", "interleukin-1 ", "interleukin-10 ", 
"interleukin-12 ", "interleukin-18 ", "interleukin-6 ", "kappa", 
"migration", "stress", "taxis", "wound"), class = "factor")), .Names = c("GO", 
"PosCount", "shortgo"), class = "data.frame", row.names = c(NA, 
6L))

看起来像这样:

> tdf
                                                  GO PosCount  shortgo
1             Cytokine-cytokine receptor interaction       17 cytokine
2 Cytokine-cytokine receptor interaction|Endocytosis       18 cytokine
3                I-kappaB kinase/NF-kappaB signaling        4    kappa
4                       NF-kappa B signaling pathway        5    kappa
5                      NF-kappaB import into nucleus        1    kappa
6                                  T cell chemotaxis        2    taxis

我想要做的是根据shortgo拆分数据框,然后按GO对其PosCount成员进行排序,产生此结果(手工制作):

$cytokine
[1] Cytokine-cytokine receptor interaction|Endocytosis
[2] Cytokine-cytokine receptor interaction 

$kappa
[1] NF-kappa B signaling pathway
[2] I-kappaB kinase/NF-kappaB signaling 
[3] NF-kappaB import into nucleus

$taxis
[1] T cell chemotaxis

我坚持这个:

> split(tdf$GO,tdf$shortgo)
Error in split.default(tdf$GO, tdf$hsortgo) : 
  group length is 0 but data length > 0

我该怎么办呢?

2 个答案:

答案 0 :(得分:5)

您可以在拆分之前先订购数据框:

library(dplyr)
tdf <- tdf %>% group_by(shortgo) %>% arrange(desc(PosCount))

然后拆分:

ldf <- split(tdf$GO, tdf$shortgo, drop=TRUE)

给出了所需的(有序)输出:

> ldf
$cytokine
[1] "Cytokine-cytokine receptor interaction|Endocytosis"
[2] "Cytokine-cytokine receptor interaction"            

$kappa
[1] "NF-kappa B signaling pathway"       
[2] "I-kappaB kinase/NF-kappaB signaling"
[3] "NF-kappaB import into nucleus"      

$taxis
[1] "T cell chemotaxis"

如果要将数据框拆分为数据框列表,可以使用:

ldf <- split(tdf, tdf$shortgo, drop=TRUE)

基础R(provided by @Henrik in the comments)的解决方案:

split(tdf$GO[order(tdf$shortgo, -tdf$PosCount)], tdf$shortgo, drop=TRUE)

答案 1 :(得分:2)

使用data.table,您可以使用setorder() to reorder your data.table by reference,然后按如下方式分组:

require(data.table)
ans = setorder(setDT(tdf), shortgo, -GO)[, .(GO_list = list(GO)), by=shortgo]

我建议保留它,因为它更容易执行计算。但如果你坚持你的最终结构,那么你可以这样做:

ans = setattr(ans$GO_list, 'names', as.character(ans$shortgo))

如果您不希望通过引用重新排序原始数据,可以执行以下操作:

ans = setDT(tdf)[order(shortgo, -GO), .(GO_list = list(GO)), by=shortgo]