在R中的if操作之后添加数字

时间:2015-05-29 14:18:42

标签: r countif

我有一组数据,其中包括患者在某个特定日期服用的药物数量。

subject<-c(111,111,111,222,222,333,333,333,333)
date<-as.Date(c("2010-12-12","2011-12-01","2009-8-7","2010-5-7","2011-3-7","2011-8-5","2013-8-27","2016-9-3","2011-8-5"))
medicationCourses<-c(1,0,NA,3,4,2,4,5,6)

data<-data.frame(subject,date,medicationCourses)

data

  subject      date        medicationCourses
1     111    2010-12-12             1
2     111    2011-12-01             0
3     111    2009-08-07             NA
4     222    2010-05-07             3
5     222    2011-03-07             4
6     333    2011-08-05             2
7     333    2013-08-27             4
8     333    2016-09-03             5
9     333    2011-08-05             6

我也有他们的入院日期。

hospitalSubject<-c(111,222,333)
admissionDate<-as.Date(c("2011-12-31","2013-12-31","2013-12-31"))

hospitalData<-data.frame(hospitalSubject,admissionDate)

hospitalData

  hospitalSubject admissionDate
1             111    2011-12-31
2             222    2013-12-31
3             333    2013-12-31

我想在入院日期或之前总结药物疗程的数量,并产生以下结果:

subject    admissionDate   totalMedicationCourses
 111         2011-12-31            1
 222         2013-12-31            7
 333         2013-12-31            12

我想知道是否有人能告诉我如何在R中做到这一点?我是R的新手用户,所以任何指导都会非常感谢!

1 个答案:

答案 0 :(得分:1)

一个选项是merge两个数据集中subject/hospitalSubject的两个数据集subset date <= admissionDate sum行,并获得aggregate的{​​{1}} 'medicaCourses'按'subject / admissionDate'分组d1 <- subset(merge(data, hospitalData, by.x='subject', by.y='hospitalSubject'), date <= admissionDate) aggregate(medicationCourses~subject+admissionDate, d1, sum, na.rm=TRUE, na.action=NULL) # subject admissionDate medicationCourses #1 111 2011-12-31 1 #2 222 2013-12-31 7 #3 333 2013-12-31 12

data.table

或者我们可以通过将'data.frame'转换为'data.table'(setDT(data))来使用setkey(,将密钥设置为'subject'(hospitalData),以及加入date <= admissionDate,过滤sum行并获取'{1}}'药物课程',按'主题'和'admissionDate'分组。

library(data.table)
setkey(setDT(data), subject)[hospitalData][date <= admissionDate, 
  list(TotalMedicationCourses=sum(medicationCourses, na.rm=TRUE)),
        list(subject, admissionDate)]
#    subject admissionDate TotalMedicationCourses
#1:     111    2011-12-31                      1
#2:     222    2013-12-31                      7
#3:     333    2013-12-31                     12

使用dplyr

的类似方法
library(dplyr)
  left_join(data, hospitalData, by=c('subject'='hospitalSubject')) %>%
        filter(date <=admissionDate) %>% 
        group_by(subject, admissionDate) %>% 
        summarise(TotalMedicationCourses=sum(medicationCourses, na.rm=TRUE))