根据R

时间:2016-06-28 18:43:59

标签: r dataframe data.table

我们将从以下DataTable开始:

    id       date
 1:  1 2015-12-31
 2:  1 2014-12-31
 3:  1 2013-12-31
 4:  1 2012-12-31
 5:  1 2011-12-31
 6:  2 2015-12-31
 7:  2 2014-12-31
 8:  2 2014-01-25
 9:  2 2013-01-25
10:  2 2012-01-25

library(data.table)
DT <- data.table(c(1, 1, 1, 1, 1, 2, 2, 2, 2, 2),
                 as.IDate(c("2015-12-31", "2014-12-31", "2013-12-31", "2012-12-31", 
                            "2011-12-31", "2015-12-31", "2014-12-31", "2014-01-25",
                            "2013-01-25", "2012-01-25")))
setnames(DT, c("id", "date"))

对于每个唯一ID,我想创建一个排名。特定id的最新日期应该等级为0.我应该从该日期删除一年以获得排名-1。如果月份与0级日期不同,我们应该停止排名。例如,在第8行,对于id = 2,由于月份不是12月,我们应该停止排名。

我们会得到以下结果:

    id       date rank_year
 1:  1 2015-12-31         0
 2:  1 2014-12-31        -1
 3:  1 2013-12-31        -2
 4:  1 2012-12-31        -3
 5:  1 2011-12-31        -4
 6:  2 2015-12-31         0
 7:  2 2014-12-31        -1
 8:  2 2014-01-25        NA
 9:  2 2013-01-25        NA
10:  2 2012-01-25        NA

到目前为止,我有以下代码(由@Frank和@akrun提供):

DT <- DT[order(id, -date)]
DT <- DT[,rank_year := { z = month(date) + year(date)*12
                         as.integer( (z - z[1L])/12) # 12 months
                       }, by = id]

    id       date rank_year
 1:  1 2015-12-31         0
 2:  1 2014-12-31        -1
 3:  1 2013-12-31        -2
 4:  1 2012-12-31        -3
 5:  1 2011-12-31        -4
 6:  2 2015-12-31         0
 7:  2 2014-12-31        -1
 8:  2 2014-01-25        -1
 9:  2 2013-01-25        -2
10:  2 2012-01-25        -3

1 个答案:

答案 0 :(得分:6)

好的,我想我会这样做

var test = function(options){
    var that = {};
    // you can use type, file & breaking point with option.type options.file etc..
    that.reset = function() {
        $("#result4").html("new text");
        console.log("OK");
    };

    return that;
};

有关其工作原理的详细信息,请参阅DT[, rank_year := replace( year(date) - year(date)[1L], month(date) != month(date[1L]), NA_integer_ ), by=id] id date rank_year 1: 1 2015-12-31 0 2: 1 2014-12-31 -1 3: 1 2013-12-31 -2 4: 1 2012-12-31 -3 5: 1 2011-12-31 -4 6: 2 2015-12-31 0 7: 2 2014-12-31 -1 8: 2 2014-01-25 NA 9: 2 2013-01-25 NA 10: 2 2012-01-25 NA

扩展旧答案的一种方法是

?replace