【问题标题】:Custom function within subset of data, base functions, vector output?数据子集中的自定义函数、基本函数、向量输出?
【发布时间】:2023-04-11 05:58:01
【问题描述】:

为半“双重职位”道歉。我觉得我应该能够破解这个,但我正在兜圈子。这与我之前很好回答的问题类似:

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")
)

我想做的是标记第一次访问(如 DOV)距离诊断 (DOD) 不到 180 天的对象。我从 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 函数很好,它制作了一个“查找”表,我可以在其中查看哪些 ID 在诊断后 180 天内首次访问,然后我可以进行原始测试并通过并制作一个指标变量,但是我应该能够做到这一点,这是我认为的一步。

如果可能的话,我也想使用 base。我有一个带有“by”的方法,但它再次为每个 ID 提供了一个结果,并且也是一个列表。一直在尝试聚合,但得到诸如“必须是一个列表”之类的东西,然后是“它的长度不一样”,并使用输入的公式方法,我被难住了“cbind(DOV,DOD)〜ID”......

欣赏输入,渴望学习!

【问题讨论】:

    标签: r


    【解决方案1】:

    在围绕这些日期列的创建包装 as.Date 之后,假设名为“test”的 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
    

    【讨论】:

      【解决方案2】:

      我已经添加到 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)
      

      代码

      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)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-02
        • 2023-04-01
        • 2019-08-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多