簡體   English   中英

從 R 中數據幀的列中獲取 `n` 個最大值或最小值

[英]Getting `n` max or min values from column of a dataframe in R

我有大數據框。 我想找到某個列的第n最低元素的行索引。 例如:考慮以下數據幀df

col_1 col_2 col_3
  1      2     3 
  -1     2     21 
  2      3     1 

所以func(dataframe = df, column_name = col_1, n=2)會返回我

[1,2] #index of the rows

注意:我想避免對列進行排序。

一個有趣的問題。 我能想到(至少)四種方法; 全部使用基本 R 解決方案。 為簡單起見,我只是創建了一個向量,而不是使用數據框。 如果它適用於向量,只需對數據框進行子集化。

首先是一些虛擬數據

x = runif(1e6)

現在四種方法(按速度排序)

## Using partial sorting
f = function(n){
  cut_off = sort(x, partial=n+1)[n+1]
  x[x < cut_off]
}

## Using a faster method of sorting; but doesn't work with partial
g = function(n){
  cut_off = sort(x, method="radix")[n+1]
  x[x < cut_off]
}

# Ordering
h = function(n) x[order(x)[1:n]]

#Ranking
i = function(n) x[rank(x) %in% 1:n]

時間表明,仔細排序似乎是最佳選擇。

R> microbenchmark::microbenchmark(f(n), g(n), h(n),i(n), times = 4)
Unit: milliseconds
 expr    min     lq   mean median     uq    max neval  cld
 f(n)  112.8  116.0  122.1  122.6  128.1  130.2     4 a   
 g(n)  372.6  379.1  442.6  386.1  506.1  625.6     4  b  
 h(n) 1162.3 1196.0 1222.0 1238.4 1248.0 1248.8     4   c 
 i(n) 1414.9 1437.9 1489.1 1484.4 1540.3 1572.6     4    d

要使用數據框,您將具有以下內容:

cut_off = sort(df$col, partial=n+1)[n+1]
df[df$col < cut_off,]

使用排序,但這是一種方法。

set.seed(1)
nr    = 100
nc    = 10
n     = 5
ixCol = 1
input = matrix(runif(nr*nc),nrow = nr,ncol=nc)
input[head(order(input[,ixCol]),n),]

使用dplyr和(為了更簡單的代碼) magrittr

data(iris) # use iris dataset

library(dplyr); library(magrittr) # load packages

iris %>%
  filter(Sepal.Length %in% sort(Sepal.Length)[1:3])

這將輸出具有最低 3 個Sepal.Length值的行,而不對數據框進行排序。 在這種情況下有關系,所以它輸出四行。

要獲取相應的行名稱,您可以使用以下內容:

rownames(subset(iris,
            Sepal.Length %in% sort(Sepal.Length)[1:3]))

暫無
暫無

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

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