简体   繁体   English

在 R 中按条件值过滤

[英]Filtering by conditional values in R

So, my data take the general shape of:因此,我的数据采用以下一般形式:

library(tidyverse)

id <- c(1, 1, 2, 2, 3, 3)
group <- c("A", "B", "A", "A", "B", "B")
value <- c(34, 12, 56, 78, 90, 91)

df <- tibble(id, group, value)
df

     id group value
  <dbl> <chr> <dbl>
1     1 A        34
2     1 B        12
3     2 A        56
4     2 A        78
5     3 B        90
6     3 B        91

What I want to do can be described as "for each id, take the maximum value of group A. But, if A is not there, take the maximum value of group B."我想要做的可以描述为“对于每个id,取A组的最大值。但是,如果A不在,则取B组的最大值。” So my desired output would look something like:所以我想要的输出看起来像:

     id group value
  <dbl> <chr> <dbl>
1     1 A        34
4     2 A        78
6     3 B        91

I tried to do this using the code...我尝试使用代码来做到这一点......

desired <- df %>%
  group_by(id) %>%
  filter(if (exists(group == "A")) max(value) else if (exists(group == "B")) (max(value)))

...but I received an error. ...但我收到一个错误。 Help?帮助?

One option could be:一种选择可能是:

df %>%
 group_by(id) %>%
 arrange(group, desc(value), .by_group = TRUE) %>%
 slice(which.max(group == "A"))

     id group value
  <dbl> <chr> <dbl>
1     1 A        34
2     2 A        78
3     3 B        91

Here is a base R option这是一个基本的 R 选项

subset(
  df[order(id, group, -value), ],
  ave(rep(TRUE, nrow(df)), id, FUN = function(x) seq_along(x) == 1)
)

which gives这使

     id group value
  <dbl> <chr> <dbl>
1     1 A        34
2     2 A        78
3     3 B        91

The basic idea is:基本思想是:

  • We reorder the rows of df via df[order(id, group, -value), ]我们通过df[order(id, group, -value), ]df的行重新排序
  • Then we take the first value in the reordered df by id然后我们根据id取重新排序的df的第一个value

Using data.table使用数据data.table

library(data.table)
setDT(df)[order(id, group, -value), .SD[1], id]
#    id group value
#1:  1     A    34
#2:  2     A    78
#3:  3     B    91

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

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