简体   繁体   English

R中数据帧中的条件子集

[英]Conditional subset in data frame in R

I have a data frame in R that looks like this:我在 R 中有一个数据框,如下所示:

Id   group   category number
001  1       A        0.10
001  1       B        0.15
002  2       A        0.55
003  3       A        0.75
003  3       B        0.45

Now, I would like to have only one row per Id .现在,我希望每个Id只有一行。 For Id's in groups 1 and 2, the row which category is B should primarily be used.对于groups 1 和groups 2 中的 Id,应主要使用category为 B 的行。 If there for groups 1 or 2 are no rows where the category is B, then category A should be used.如果第 1 groups或第 2 groups没有category为 B 的行,则应使用category A。 For Id's which group is 3, the row where the category is A should always be used.对于group为 3 的Id's ,应始终使用category为 A 的行。

The output should look like this输出应该是这样的

Id   group   category number
001  1       B        0.15
002  2       A        0.55
003  3       A        0.75

How could this be done in R?这怎么能在 R 中完成?

We could use slice我们可以使用slice

library(dplyr)
df1 %>% 
   group_by(Id) %>%
   slice(max(match('B', category, nomatch = 0), 1))

data数据

df1 <- structure(list(Id = c("001", "001", "002", "003", "003"), group = c(1L, 
1L, 2L, 3L, 3L), category = c("A", "B", "A", "A", "B"), number = c(0.1, 
0.15, 0.55, 0.75, 0.45)), row.names = c(NA, -5L), class = "data.frame")

Since B comes after A , we'll sort by category descending and keep one row per group, filtering out the group 3 / category A rows per your suggestion.由于BA之后,我们将按类别降序排序,每组保留一行,根据您的建议过滤掉第 3 组/类别 A 的行。

library(dplyr) 
your_data %>%
  filter(!(group == 3 & category == "A")) %>%
  group_by(Id, group) %>%
  arrange(desc(category)) %>%
  slice(1)

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

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