user5739619 user5739619 - 1 month ago 5
R Question

Extract certain number of rows in dataframe based on condition in R?

Let's say I have a dataframe

Group Pos Score
A V 82
A V 72
A W 95
A W 92
A W 65
A W 61
A X 82
A X 80
A X 70
B V 88
B V 77
B W 95
B W 91
B W 85
B W 71
B X 88
B X 83
B X 78
...
#this data frame has groups with values C, D, E, etc also


Let's say I want to keep the top number of scores for each
Group
, and each
Pos
. For example, let's say I want to keep the top 1
Score
for
Pos=V
, top 3
Score
s for
Pos=W
, and top 2
Score
s of
Pos=X


So I want the dataframe to look like

Group Pos Score
A V 82
A W 95
A W 92
A W 65
A X 82
A X 80
B V 88
B W 95
B W 91
B W 85
B X 88
B X 83


How can I do this in R?

Answer

We can try

v1 <- unique(df1$Pos)
Map(function(x,y)
   filter(df1, Pos==x) %>%
       group_by(Group) %>% 
       top_n(y, wt = Score), v1, c(1, 3, 2)) %>% 
   bind_rows()