如何根据条件过滤数据?

时间:2019-11-28 12:21:18

标签: r dplyr

我有一个数据集,如下所示:

df_A <- tribble(
  ~id,       ~type,     ~min_price,  ~max_price,
  "1",        "X",          10,          40,
  "1",        "Y",          20,          50,
  "1",         NA,          15,          70,
  "1",        "X",          40,          90,
  "1",        "Y",          23,         100,
  "2",        "X",          18,          40,
  "2",        "Y",          34,          50,
  "2",        "Y",          64,         150,
  "2",         NA,          15,          70,
  "3",        "X",          40,          90,
  "3",        "Y",          23,         100,
)

现在,我想操纵数据来回答这个问题:“当“类型”为X时,每个ID的最低价格是多少?”或“当“类型”为Y时,每个ID的最低价格是多少?”

desired_DF <- tribble(
  ~id,       ~type,     ~min_price,  ~max_price,
  "1",        "X",          10,          40,
  "1",        "Y",          20,          50,
  "2",        "X",          18,          40,
  "2",        "Y",          34,          50,
  "2",         NA,          15,          70,
  "3",        "X",          40,          90,
  "3",        "Y",          23,         100,
)

有人可以帮我得到这个吗?

2 个答案:

答案 0 :(得分:1)

可以使用dplyr软件包来计算此类摘要统计信息。

library(dplyr)

df_A %>%
  group_by(id, type) %>%
  summarise(min_price = min(min_price),
    max_price= max(max_price))

答案 1 :(得分:0)

是这样吗?

df_A %>% filter(type=="X") %>% group_by(id) %>% summarize(m=min(min_price))