Home > Enterprise >  filter rows by minimum value relative to a factor column
filter rows by minimum value relative to a factor column

Time:05-31

i need to filter a DF by the minimum value relative to a column. Example:

RowNumber Some_Factor Value One_of_many_random_columns
1 A 10 Hello World!
2 A 15 Hello World!
3 A 8 Hello World!
4 B 20 Hello Again!
5 B 18 Hello Again!
6 B 25 Hello Again!

In this example I would like to filter rows 3 & 5. because they have the minimum DF$Value relative to DF$Some_Factor.

thanks in advance.

CodePudding user response:

df %>%
  group_by(Some_Factor) %>%
  filter(Value == min(Value))

CodePudding user response:

We could use slice_min after group_by:

library(dplyr)

df %>% 
  group_by(Some_Factor) %>% 
  slice_min(Value) %>%
  ungroup()

  RowNumber Some_Factor Value One_of_many_random_columns
      <int> <chr>       <int> <chr>                     
1         3 A               8 Hello World!              
2         5 B              18 Hello Again!  

CodePudding user response:

Using ave in subset.

subset(dat, Some_Factor == ave(Some_Factor, RowNumber, FUN=min))
#   RowNumber Some_Factor Value One_of_many_random_columns
# 3         A           8 Hello                     World!
# 5         B          18 Hello                     Again!

Data:

dat <- structure(list(RowNumber = c("A", "A", "A", "B", "B", "B"), Some_Factor = c(10L, 
15L, 8L, 20L, 18L, 25L), Value = c("Hello", "Hello", "Hello", 
"Hello", "Hello", "Hello"), One_of_many_random_columns = c("World!", 
"World!", "World!", "Again!", "Again!", "Again!")), class = "data.frame", row.names = c("1", 
"2", "3", "4", "5", "6"))

CodePudding user response:

data.table option:

library(data.table)
setDT(df)[ , .SD[which.min(Value)], by = Some_factor]

Output:

   Some_factor RowNumber Value One_of_many_random_columns
1:           A         3     8               Hello World!
2:           B         5    18               Hello Again!

Data

df <- data.frame(RowNumber = c(1,2,3,4,5,6),
                 Some_factor = c("A", "A", "A", "B", "B", "B"),
                 Value = c(10,15,8,20,18,25),
                 One_of_many_random_columns = c("Hello World!", "Hello World!", "Hello World!", "Hello Again!", "Hello Again!", "Hello Again!"))
  • Related