简体   繁体   English

按相对于因子列的最小值过滤行

[英]filter rows by minimum value relative to a factor column

i need to filter a DF by the minimum value relative to a column.我需要通过相对于列的最小值过滤 DF。 Example:例子:

RowNumber行号 Some_Factor Some_Factor Value价值 One_of_many_random_columns One_of_many_random_columns
1 1 A一个 10 10 Hello World!你好世界!
2 2 A一个 15 15 Hello World!你好世界!
3 3 A一个 8 8 Hello World!你好世界!
4 4 B 20 20 Hello Again!再一次问好!
5 5 B 18 18 Hello Again!再一次问好!
6 6 B 25 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 .在此示例中,我想过滤第 3 行和第 5 行。因为它们具有相对于DF$Some_Factor的最小DF$Value

thanks in advance.提前致谢。

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

We could use slice_min after group_by :我们可以在group_by之后使用slice_min

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!  

Using ave in subset .subset使用ave

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"))

data.table option: data.table选项:

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!"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM