vicky
vicky

Reputation: 415

How to divide between groups of rows using dplyr

I have the similar data and I want the exact result as what this link states: How to divide between groups of rows using dplyr?

However, the only difference with my data is that sometimes column "condition" does not have "A" or "B" all the time, so there's no denominator or numerator sometimes.

x <- data.frame(
    name = rep(letters[1:4], each = 2),
    condition = rep(c("A", "B"), times = 4),
    value = c(2,10,4,20,8,40,20,100)
) 
x = x[-c(4,5),] #this is my dataframe

I want to remove rows that do not always have both A and B and continue the division. Can anyone show me how to do that based on this code?

x %>% 
  group_by(name) %>%
  summarise(value = value[condition == "B"] / value[condition == "A"])

Upvotes: 2

Views: 282

Answers (2)

akrun
akrun

Reputation: 887851

We can use data.table

library(data.table)
setDT(x)[all(c('A', 'B') %chin% condition), 
    .(value = value[condition == 'B']/value[condition == 'A']), name]

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 389235

You could remove the groups which do not have "A" or "B" and then divide.

library(dplyr)

x %>%
  group_by(name) %>%
  filter(all(c('A', 'B') %in% condition)) %>%
  summarise(value = value[condition == "B"] / value[condition == "A"])

#  name  value
#  <fct> <dbl>
#1 a         5
#2 d         5

Upvotes: 2

Related Questions