Kactus
Kactus

Reputation: 122

Subset data frame based on multiple conditions?

I have a data frame: df=data.frame(sample.id=c(1, 1, 2, 3, 4, 4, 5, 6, 7, 7), sample.type=c(U, S, S, U, U, D, D, U, U, D), cond = c(1.4, 17, 12, 0.45, 1, 7, 1, 9, 0, 14))

I want a data frame that only contains the rows of sample.ids that have both sample.type "U" and sample.type "D"

new df: df.new=data.frame(sample.id=c(4, 4, 7, 7), sample.type=c(U, D, U, D), cond = c(1, 7, 0, 14))

What's the easiest way to do this? Duplicated doesn't work because it will return sample.ids with U and S as well as U and D. I can't figure out how to filter/subset for sample ids that are both sample.type U and sample.type D. Thanks for any advice!

Upvotes: 1

Views: 153

Answers (3)

IceCreamToucan
IceCreamToucan

Reputation: 28675

With data.table

library(data.table)
setDT(df)

df[, if(all(c('U', 'D') %in% sample.type)) .SD, by = sample.id]

Upvotes: 1

BENY
BENY

Reputation: 323226

Using filter with any

df %>% group_by(sample.id) %>% filter(any(sample.type == 'U') & any(sample.type == 'D'))
# A tibble: 4 x 3
# Groups:   sample.id [2]
  sample.id sample.type  cond
      <dbl>      <fctr> <dbl>
1         4           U     1
2         4           D     7
3         7           U     0
4         7           D    14

Upvotes: 1

akrun
akrun

Reputation: 886938

We can do a filter by group

library(dplyr)
df %>% 
   group_by(sample.id) %>% 
   filter(all(c("U", "D") %in% sample.type))
# A tibble: 4 x 3
# Groups:   sample.id [2]
#  sample.id sample.type  cond
#      <dbl> <fct>       <dbl>
#1         4 U               1
#2         4 D               7
#3         7 U               0
#4         7 D              14

Upvotes: 2

Related Questions