[英]R: returning the 5 rows with the highest values
樣本數據
mysample <- data.frame(ID = 1:100, kWh = rnorm(100))
我正在嘗試自動化返回包含特定列中5個最高值的數據框中的行的過程。 在示例數據中,可以使用以下代碼找到“kWh”列中的5個最高值:
(tail(sort(mysample$kWh), 5))
在我的情況下返回:
[1] 1.477391 1.765312 1.778396 2.686136 2.710494
我想創建一個包含第2列中包含這些數字的行的表。我正在嘗試使用此代碼:
mysample[mysample$kWh == (tail(sort(mysample$kWh), 5)),]
返回:
ID kWh
87 87 1.765312
我希望它能在“kWh”列中返回包含上圖中的r行。 我確定我錯過了一些基本的東西,但我無法理解。
我們可以使用rank
mysample$Rank <- rank(-mysample$kWh)
head(mysample[order(mysample$Rank),],5)
如果我們不需要創建列,直接使用order
(如在三種替代方法中提到的@Jaap)
#order descending and get the first 5 rows
head(mysample[order(-mysample$kWh),],5)
#order ascending and get the last 5 rows
tail(mysample[order(mysample$kWh),],5)
#or just use sequence as index to get the rows.
mysample[order(-mysample$kWh),][1:5]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.