在R Data.Table中创建一个计数器列,并在另一列上创建条件

时间:2018-09-24 23:56:35

标签: r data.table

我试图计算自记录的历史以来产品提供的年限。

在下面的示例中,我想在记录的第一个非零销售额处启动计数器。

请注意,未来几年我的销售记录可能为零,但计数器应将该年视为有效。

我试验了rleid,但无法找出区分初始0和寿命内0的方法。

tt <- data.table(YEAR=2007:2018,
                 SALES=c(0,0,0,2,3,5,1,0,9,0,3,4),
                 YEARS_IN=c(0,0,0,1,2,3,4,5,6,7,8,9))

> tt
    YEAR SALES YEARS_IN
 1: 2007     0        0
 2: 2008     0        0
 3: 2009     0        0
 4: 2010     2        1
 5: 2011     3        2
 6: 2012     5        3
 7: 2013     1        4
 8: 2014     0        5
 9: 2015     9        6
10: 2016     0        7
11: 2017     3        8
12: 2018     4        9

2 个答案:

答案 0 :(得分:2)

这里是使用基数R的单行解决方案-

tt <- data.table::data.table(YEAR=2007:2018,
                 SALES=c(0,0,0,2,3,5,1,0,9,0,3,4),
                 YEARS_IN=c(0,0,0,1,2,3,4,5,6,7,8,9))

tt$Calc_Years <- cumsum(cumsum(tt$SALES) > 0)
tt
    YEAR SALES YEARS_IN Calc_Years
 1: 2007     0        0          0
 2: 2008     0        0          0
 3: 2009     0        0          0
 4: 2010     2        1          1
 5: 2011     3        2          2
 6: 2012     5        3          3
 7: 2013     1        4          4
 8: 2014     0        5          5
 9: 2015     9        6          6
10: 2016     0        7          7
11: 2017     3        8          8
12: 2018     4        9          9

感谢Simon,这是一个data.table版本-

tt[ , Calc_Years := cumsum(cumsum(SALES) > 0)]

答案 1 :(得分:0)

library(data.table)
tt <- data.table(YEAR=2007:2018,
                 SALES=c(0,0,0,2,3,5,1,0,9,0,3,4),
                 YEARS_IN=c(0,0,0,1,2,3,4,5,6,7,8,9))
temp <- min(which(tt[,SALES]!=0))
tt[-c(1:(temp-1)),Comp:=.I]
tt[c(1:(temp-1)),Comp:=0]
tt

    YEAR SALES YEARS_IN Comp
 1: 2007     0        0    0
 2: 2008     0        0    0
 3: 2009     0        0    0
 4: 2010     2        1    1
 5: 2011     3        2    2
 6: 2012     5        3    3
 7: 2013     1        4    4
 8: 2014     0        5    5
 9: 2015     9        6    6
10: 2016     0        7    7
11: 2017     3        8    8
12: 2018     4        9    9