如何使用dplyr在行组之间进行划分 [英] How to divide between groups of rows using dplyr

查看:47
本文介绍了如何使用dplyr在行组之间进行划分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有相似的数据,我想要确切的结果作为此链接所陈述的内容:如何使用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?

但是,与我的数据的唯一区别是有时条件"列有时始终没有"A"或"B",因此有时没有分母或分子.

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

我想删除不总是同时具有A和B的行,并继续进行除法.谁能告诉我如何根据此代码执行该操作?

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

推荐答案

您可以删除不包含"A"或"B"的组,然后进行划分.

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

这篇关于如何使用dplyr在行组之间进行划分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆