R:根据组和不同条件对数据框进行分组

时间:2019-04-17 20:28:01

标签: r dplyr subset

考虑数据框:

data = data.frame(a=c(1,1,1,2,2,3),
              b=c("apples", "oranges", "apples", "apples", "apples", "oranges"),
              c=c(12, 22, 22, 45, 67, 28), 
              d=c("Monday", "Monday", "Monday", "Tuesday", "Wednesday", "Tuesday"),
              out = c(12, 14, 16, 18, 20, 22),
              rate = c(-0.01, -0.02, 0.03, -0.04, 0.07, 0.06))

我想对数据框进行分组,以在水果为苹果时速率为负时保持值,而在水果为橙色时速率为正时保持值。即我想要的输出是

data = data.frame(a=c(1,2,3),
              b=c("apples", "apples", "oranges"),
              c=c(12, 45, 28), 
              d=c("Monday", "Tuesday", "Tuesday"),
              out = c(12, 18, 22),
              rate = c(-0.01, -0.04, 0.06))

有办法吗?

2 个答案:

答案 0 :(得分:2)

这是一个dplyr解决方案:

library(dplyr)
data %>% 
  filter((b == "apples" & rate < 0) | (b == "oranges" & rate > 0))

  a       b  c       d out  rate
1 1  apples 12  Monday  12 -0.01
2 2  apples 45 Tuesday  18 -0.04
3 3 oranges 28 Tuesday  22  0.06

答案 1 :(得分:1)

我不知道如何处理dplyr。但是,您可以使用subset

轻松完成此操作
data = data.frame(a=c(1,1,1,2,2,3),
              b=c("apples", "oranges", "apples", "apples", "apples", "oranges"),
              c=c(12, 22, 22, 45, 67, 28), 
              d=c("Monday", "Monday", "Monday", "Tuesday", "Wednesday", "Tuesday"),
              out = c(12, 14, 16, 18, 20, 22),
              rate = c(-0.01, -0.02, 0.03, -0.04, 0.07, 0.06))

subData <- subset(data, (b == "apples" & rate < 0) | (b == "oranges" & rate > 0))

代码非常简单。它是data的子集,用于寻找您的两个约束。在此代码中,&代表and,而|代表or