根据行条件创建列

时间:2017-12-15 09:45:42

标签: r multiple-columns mutate

我有一个看起来像这样的数据集

user_id  Gap itr    visit_no.(desired column)
      a  0.3   1            1
      a  0.5   1            1
      a  1.5   1            1
      a  0.9   1            2
      a  2.6   1            2
      a 0.34   1            3
      a  0.8   2            1
      a 0.34   2            1
      b  1.6   1            1
      b  0.7   1            2
      b  0.8   1            2
      b  0.7   1            2
      b  4.8   2            1
      b 0.39   2            2
      b 0.38   2            2
      b 0.89   2            2

我想创建列(visit_no。)。每当间隙大于1时,我们需要增加visit_no。在下一行中将值减1并且它将保持相同,直到我们找到另一个值> 1,我们将继续按递增顺序分配序列号。如果间隙小于1,则visit_no的值将在visit_no的先前行中给出。并且visit_no。总是从1开始为用户和itr ..Visit_No列按user_id和itr分组

这是数据框

df<-data.frame(user=c("a","a","a","a","a","a","a","a","b","b","b","b","b","b","b","b")
                    , gap=c(0.3,0.5,1.5,0.9,2.6,0.34,0.8,0.34,1.6,0.7,0.8,0.7,4.8,0.39,0.76,0.72),
                     itr=c(1,1,1,1,1,1,2,2,1,1,1,1,2,2,2,2))

2 个答案:

答案 0 :(得分:2)

forAll { arbitraryEvent: ClientFacingExecution =>
      val unmatchedEvent = ClientFacingExecutionEnriched(arbitraryFoExec)
      val expectedId = unmatchedEvent.clientFacingExecution.id

      ........................................
      ........................................
      ........................................

      cacheUnderTest.records should have size 1
}

答案 1 :(得分:1)

这与AntoniosK答案非常相似,但在data.table中,没有管道运算符,data.table的{​​{1}} - 函数。

shift