简体   繁体   中英

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"])

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

We can use data.table

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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