[英]Filter Data Per Value of Independent Variable in R
我一般對R和數據處理還很陌生,所以如果我對術語的使用不佳,請原諒我。
我有一些數據,這些數據帶有離散的,非唯一的獨立變量DeltaT和一個稱為Score的因數值。
我只想保留DeltaT中每個值的得分最高的5個百分點(刪除所有LT 0.95個百分點)。
下圖描述了我要完成的工作。
我給人留下了沒有循環的方法,但是不知道我可能需要的函數的名稱。
沒有您的數據,我創建了自己的數據。 這是一種可以使用分位數函數獲取第95個百分位數值並使用dplyr
程序包的分組和過濾功能來幫助您解決問題的方法:
library(dplyr)
df <- data.frame(DeltaT = c(rep(1, 10), rep(2, 10)), Score = c(1:10, 1:10))
df %>% group_by(DeltaT) %>% filter(Score >= quantile(Score, probs = 0.95))
在這種情況下,輸出將是因為只有這兩個分數與第95個百分點或更高匹配:
Source: local data frame [2 x 2]
Groups: DeltaT [2]
DeltaT Score
<dbl> <int>
1 1 10
2 2 10
您可以根據自己的特定需求更改代碼。
這是使用quantile()
, ave()
,比較和索引的基本R解決方案:
df <- data.frame(DeltaT=c(1L,1L,1L,2L,2L,3L,3L,3L,3L,4L,4L,4L),Score=1:12);
df[df$Score>=ave(df$Score,df$DeltaT,FUN=function(x) quantile(x,0.95)),];
## DeltaT Score
## 3 1 3
## 5 2 5
## 9 3 9
## 12 4 12
您的示例數據並不理想,因為它不包含滿足過濾條件的多個Score
值的情況。 我在假設您要保留所有滿足條件的行的前提下編寫解決方案。 這是一個更好的測試:
df <- data.frame(DeltaT=c(1L,1L,1L,2L,2L,3L,3L,3L,3L,4L,4L,4L,4L),Score=c(1:12,12));
df[df$Score>=ave(df$Score,df$DeltaT,FUN=function(x) quantile(x,0.95)),];
## DeltaT Score
## 3 1 3
## 5 2 5
## 9 3 9
## 12 4 12
## 13 4 12
嘗試這個:
library(data.table)
setDT(df) # convert your dataset into a data.table
output <- df[ score > quantile(df$score, c(.95)), # filter condition
.(score=score), # output column
by=.(DeltaT) ] # grouped by
dplyr可能會很有幫助。 假設“ df2”是您的data.frame
> library(dplyr)
> group_by(df2, DeltaT) %>% summarise(Score = round(quantile(Score, probs=0.95),0))
Source: local data frame [4 x 2]
DeltaT Score
(dbl) (dbl)
1 1 3
2 2 5
3 3 9
4 4 12
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.