How to divide between groups of rows using dplyr

不打扰是莪最后的温柔 提交于 2021-02-05 06:42:05

问题


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

回答1:


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



回答2:


We can use data.table

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


来源:https://stackoverflow.com/questions/61091598/how-to-divide-between-groups-of-rows-using-dplyr

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!