How do I do a conditional sum which only looks between certain date criteria

前端 未结 7 439
遥遥无期
遥遥无期 2020-12-18 13:47

Say I have data that looks like

date, user, items_bought, event_number
2013-01-01, x, 2, 1
2013-01-02, x, 1, 2
2013-01-03, x, 0, 3
2013-01-04, x, 0, 4
2013-0         


        
7条回答
  •  时光取名叫无心
    2020-12-18 13:56

    I like James' answer better, but here's an alternative:

    with(data,{
      sapply(split(data,user),function(x){
        sapply(x$date,function(y) sum(x$items_bought[x$date %in% c(y,y-1,y-2)]))
      })
    })
    

提交回复
热议问题