xvoraz
xvoraz

Reputation: 23

R - finding within groups

I would like to evaluate conditions within groups. While mtcars may not exactly match my data, here is my problem.

Let's to group mtcars by gear. Then I would like to get the subset of data, where within the gear group there is a row wehere 'carb' equals 1 and there is one where it is '4'. I want all the rows if there is a 1 + 4 and I would like to omit all the rows within the group if there isnt.

p <- arrange(mtcars, gear)
p <- filter(mtcars, carb == 1 & carb == 4)

This gives 0 obviously since there is not a single row where carb is has two values :)

The preferred outcome would be all the rows of mtcars where gear is 3 or 4. Omitting gear = 5 rows since within the group of gear 5, there isn't a carb == 1.

Upvotes: 0

Views: 44

Answers (2)

akrun
akrun

Reputation: 887651

An option with data.table

library(data.table)
as.data.table(mtcars)[, .SD[sum(c(1, 4) %in% carb)) == 2], gear]

Upvotes: 0

tmfmnk
tmfmnk

Reputation: 40151

You can do:

mtcars %>%
 group_by(gear) %>%
 filter(any(carb == 1) & any(carb == 4))

Or:

mtcars %>%
 group_by(gear) %>%
 filter(all(c(1, 4) %in% carb))

Upvotes: 0

Related Questions