2011-05-06 120 views
2

为半'双重职位'道歉。我觉得我应该能够解决这个问题,但我会围绕着圈子。这是一个类似的说明我以前好回答的问题:数据子集中的自定义函数,基函数,矢量输出?

Within ID, check for matches/differences

test <- data.frame(
ID=c(rep(1,3),rep(2,4),rep(3,2)), 
DOD = c(rep("2000-03-01",3), rep("2002-05-01",4), rep("2006-09-01",2)), 
DOV = c("2000-03-05","2000-06-05","2000-09-05", 
    "2004-03-05","2004-06-05","2004-09-05","2005-01-05", 
    "2006-10-03","2007-02-05") 
) 

我想要做的就是标签,其第一VIST(截至DOV)是从他们的诊断小于180天主题(DOD)。我从plyr包中获得以下内容。

ddply(test, "ID", function(x) ifelse((as.numeric(x$DOV[1]) - as.numeric(x$DOD[1])) < 180,1,0)) 

其中给出:

ID V1 
1 A 1 
2 B 0 
3 C 1 

我想是一个矢量1,1,1,0,0,0,0,1,1这样我就可以将其追加为列数据帧。基本上这个ddply函数很好,它可以创建一个'lookup'表,我可以在诊断后的180天内看到哪些ID有第一次访问,然后我可以进行原始测试并通过指标变量,但是我应该能够做到这一点是我想到的一步。

如果可能的话,我也想使用base。我有一个'by'的方法,但它只是给每个ID一个结果,也是一个列表。一直在尝试聚合,但得到的东西'必须是一个列表',然后'它不是一样的长度',并使用输入的公式方法我难住'cbind(DOV,DOD)〜ID'...

欣赏投入,热衷学习!

回答

2

周围创建日期的那些列的包装as.Date后,该返回所需标记矢量假设名为“测试”的DF是通过ID排序(并在碱完成):

# could put an ordering operation here if needed 
0 + unlist(  # to make vector from list and coerce logical to integer 
     lapply(split(test, test$ID),  # to apply fn with ID 
      function(x) rep(    # to extend a listwise value across all ID's 
        min(x$DOV-x$DOD) <180, # compare the minimum of a set of intervals 
        NROW(x))))   
11 12 13 21 22 23 24 31 32     # the labels 
1 1 1 0 0 0 0 1 1     # the values 
1

我有加入data.frame功能stringsAsFactors = FALSE:

test <- data.frame(ID=c(rep(1,3),rep(2,4),rep(3,2)), 
     DOD = c(rep("2000-03-01",3), rep("2002-05-01",4), rep("2006-09-01",2)), 
     DOV = c("2000-03-05","2000-06-05","2000-09-05","2004-03-05", 
      "2004-06-05","2004-09-05","2005-01-05","2006-10-03","2007-02-05") 
     , stringsAsFactors=FALSE) 

CODE

test$V1 <- ifelse(c(FALSE, diff(test$ID) == 0), 0, 
        1*(as.numeric(as.Date(test$DOV)-as.Date(test$DOD))<180)) 
test$V1 <- ave(test$V1,test$ID,FUN=max)