简体   繁体   English

如何使用 dplyr 在行组之间进行划分

[英]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?我有类似的数据,我想要这个链接所述的确切结果: 如何使用 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.但是,与我的数据唯一不同的是,有时“条件”列始终没有“A”或“B”,因此有时没有分母或分子。

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.我想删除并不总是同时具有 A 和 B 的行并继续除法。 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.您可以删除没有“A”或“B”的组,然后划分。

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我们可以使用data.table

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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