dplyr:基于另一列过滤

时间:2016-07-15 12:46:45

标签: r

让我们说我有以下数据,我有兴趣按日期抓取数据类型为" ts"。当然,有些日期没有ts,我需要回到真正的'这些日期的价值。

dat = data.frame(dte = c("2011-01-01","2011-02-01","2011-03-01","2011-04-01","2011-05-01",
                         "2011-01-01","2011-02-01","2011-03-01"),
                 type = c("real","real","real","real","real","ts","ts","ts"),
                 value=rnorm(8))
dat

cpy = dat %>% dplyr::filter(type == "ts") 

cpy

如何在dplyr中完成这样的事情。

预期输出为:

dte            type    value
"2011-01-01"   ts      ....
"2011-02-01"   ts
"2011-03-01"   ts  
"2011-04-01"   real
"2011-05-01"   real

3 个答案:

答案 0 :(得分:3)

您可以尝试使用基础包,

rbind(dat[dat$type == "ts",], dat[!unique(dat$dte) %in% 
                                               dat[dat$type == "ts","dte"], ])

#     dte     type       value
#6 2011-01-01   ts -0.98109206
#7 2011-02-01   ts  1.67626166
#8 2011-03-01   ts -0.06997343
#4 2011-04-01 real  1.27243996
#5 2011-05-01 real -1.63594680

type的行等于tsrbind来自real类型的剩余日期。

答案 1 :(得分:2)

一个想法可能是group_by()约会,并将值保持在type == "ts"或何时,对于给定日期,没有type == "ts",保留其他值:

dat %>%
  group_by(dte) %>%
  filter(type == "ts" | !any(type == "ts"))

给出了:

#Source: local data frame [5 x 3]
#Groups: dte [5]
#
#         dte   type      value
#      <fctr> <fctr>      <dbl>
#1 2011-04-01   real  0.2522234
#2 2011-05-01   real -0.8919211
#3 2011-01-01     ts  0.4356833
#4 2011-02-01     ts -1.2375384
#5 2011-03-01     ts -0.2242679

答案 2 :(得分:0)

使用dplyr,我们也可以使用which.max

library(dplyr)
dat %>%
    group_by(dte) %>%
    slice(which.max(factor(type)))    
#        dte   type      value
#      <fctr> <fctr>      <dbl>
#1 2011-01-01     ts -0.5052456
#2 2011-02-01     ts -0.4038810
#3 2011-03-01     ts -1.5349627
#4 2011-04-01   real  1.6812035
#5 2011-05-01   real -0.9902754

或使用与data.table

类似的选项
library(data.table)
setDT(dat)[, .SD[which.max(factor(type))] , dte]
#        dte type      value
#1: 2011-01-01   ts -0.5052456
#2: 2011-02-01   ts -0.4038810
#3: 2011-03-01   ts -1.5349627
#4: 2011-04-01 real  1.6812035
#5: 2011-05-01 real -0.9902754