用逻辑条件计算频率

时间:2017-08-04 08:49:41

标签: r

这是R代码。

illdate<-c("2009-05-26","2010-12-03","2011-06-05","2010-08-10","2009-05-14","2010-01-08","2012-08-07","2010-11-13","2013-06-06","2010-08-26")

Treated<-c("T","T","N","T","N","N","T","T","T","N")

Reason<-c("Finish","Finish","Dead","Dead","Cured","Cured","Finish","Finish","Dead","Cured")

Enddate<-c("2009-12-12","2011-05-08","2011-02-28","2010-10-30","2011-10-08","2011-03-03","2013-05-05","2011-05-06","2014-08-08","2012-07-07")

number<-c(1:10)

mydata<-data.frame(number,illdate,Treated,Reason,Enddate)

我想计算符合逻辑条件的案例数量:

1:illdate between "2010-01-01" and "2010-12-31"

2:Treated= "T"

3:Reason= "Finish" & "Cured"

4:Enddate between "2011-01-01" and "2012-12-31"

请告诉我如何在R中编写代码。非常感谢。

2 个答案:

答案 0 :(得分:3)

这是另一种方式,可能不那么漂亮:

   nrow(subset(mydata,"2010-01-01" < as.Date(illdate) & as.Date(illdate) < "2010-12-31" &
   Treated == "T" & Reason %in% c("Finish", "Cured") & 
   "2011-01-01" < as.Date(Enddate) & as.Date(Enddate) < "2012-12-31"))

答案 1 :(得分:2)

我们可以做到

res <- mydata %>%
         mutate_at(vars(matches("date")),  as.Date) %>%
         filter(between(illdate, as.Date("2010-01-01"), as.Date("2010-12-31")),
          Treated == "T",
          Reason %in% c("Finish", "Cured"),
          between(Enddate, as.Date("2011-01-01"), as.Date("2012-12-31")))

dim(res)
#[1] 2 5