How to extract the top x% of rows by group and number in R?

Viewed 171

Let's suppose I have this dataset (not the original data I am using)

data <- data.frame(
  name=c( rep("A",500), rep("B",500), rep("B",500), rep("C",20), rep('D', 100)  ),
  value=c( rnorm(500, 10, 5), rnorm(500, 13, 1), rnorm(500, 18, 1), rnorm(20, 25, 4), rnorm(100, 12, 1) )
)

I would like my code to

  1. group name
  2. arrange value in a descending way
  3. and select the top 30% but not by the value of my value variable, but the number of rows for each name

My code starts like this:

data <- data %>%
 arrange(name, value) %>%

I read about top_frac() but as far as I understand it this selects the top x percent of the values.

Thanks in advance!

1 Answers

Here is a solution. It selects the top 30% values by groups of name and then counts the rows that were selected in each group.

library(dplyr)

data %>%
  group_by(name) %>%
  arrange(name, value) %>%
  top_frac(0.30) %>%
  count(name)
#Selecting by value
## A tibble: 4 x 2
## Groups:   name [4]
#  name      n
#  <chr> <int>
#1 A       150
#2 B       300
#3 C         6
#4 D        30

It is possible to see that these numbers are in fact 30% of each group of name with

data %>% count(name) %>% mutate(n = n*0.3)
#  name   n
#1    A 150
#2    B 300
#3    C   6
#4    D  30

If you want the top 30% values, without considering the group the top values come from, then the above must be changed to the following code.

data %>%
  arrange(name, value) %>%
  top_frac(0.30) %>%
  count(name)
#Selecting by value
#  name   n
#1    A  46
#2    B 420
#3    C  20
Related