簡體   English   中英

在R數據幀的另一列中提取具有最大值的唯一行

[英]Extract the unique rows with maximum value in another column in R dataframe

我有這個名為mydf數據框。 Sample列中有重復的樣本。 我想提取具有最大total_reads的唯一樣本行並獲得result

mydf<-structure(list(Sample = c("AOGC-02-0188", "AOGC-02-0191", "AOGC-02-0191", 
"AOGC-02-0191", "AOGC-02-0194", "AOGC-02-0194", "AOGC-02-0194"
), total_reads = c(27392583, 19206920, 34462563, 53669483, 24731988, 
43419826, 68151814), Lane = c("4", "5", "4", "4;5", "5", "4", 
"4;5")), .Names = c("Sample", "total_reads", "Lane"), row.names = c("166", 
"169", "170", "171", "173", "174", "175"), class = "data.frame")

結果

  Sample        total_reads  Lane
 AOGC-02-0188    27392583    4
 AOGC-02-0191    53669483  4;5
 AOGC-02-0194    68151814  4;5

你可以aggregate然后merge

merge(aggregate(total_reads ~ Sample, mydf, max), mydf)
#        Sample total_reads Lane
#1 AOGC-02-0188    27392583    4
#2 AOGC-02-0191    53669483  4;5
#3 AOGC-02-0194    68151814  4;5

我們可以使用data.table 將'data.frame'轉換為'data.table'( setDT(mydf) ),按“Sample”分組, order對'total_reads'進行order ,並使用head對第一個觀察進行子集化。

library(data.table)
setDT(mydf)[order(-total_reads), head(.SD, 1) , Sample]

使用dplyr包,你可以這樣做:

mydf %>%
    group_by(Sample) %>% # for each unique sample
    arrange(-total_reads) %>% # order by total_reads DESC
    slice(1) # select the first row, i.e. with highest total_reads

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM