[datatable-help] To apply different instructions in data table

jholtman jholtman at gmail.com
Mon Sep 15 14:49:05 CEST 2014


try this:

        require(data.table)

        DT <- data.table(ID=c(1,1,2,2,2,3,3,4,5,5),
               
start=as.Date(c("1985-01-01","1993-07-15","1993-05-17","1998-02-25","1997-10-28","2000-05-25","1995-09-02","1998-03-01","1992-02-26","1994-07-22")),
               
end=as.Date(c("1992-05-01","1997-02-01","1997-10-20","1999-10-15","2003-08-25","2000-01-27","2002-04-15","2003-10-02","1997-03-17","2002-08-19")),
                 
reason=(c("Q2","Vacancy","R3","Vacancy","Vacancy","Vacancy","Q3","R2","S2","R1")))

        DT[
            , {
                if (all(reason != "Vacancy")){
                    indx <- which.max(end)
                    result <- list(start = min(start)
                                , end = end[indx]
                                , reason = reason[indx]
                                )
                } else {
                    if (sum(reason == "Vacancy") == 1){
                        indx <- which(reason == "Vacancy")
                        result <- list(start = min(start)
                                    , end = end[indx]
                                    , reason = reason[indx]
                                    )
                    } else {
                        indx <- which(reason == "Vacancy" & end ==
min(end[reason == "Vacancy"]))
                        result <- list(start = min(start)
                                    , end = end[indx]
                                    , reason = reason[indx]
                                    )
                    }
                }
                result
              }
            , by = ID
            ]






--
View this message in context: http://r.789695.n4.nabble.com/To-apply-different-instructions-in-data-table-tp4696925p4696950.html
Sent from the datatable-help mailing list archive at Nabble.com.


More information about the datatable-help mailing list