基于R中匹配条件的最后一行值的总体

时间:2016-10-31 05:35:26

标签: r match

我有以下输入数据。

class MyView(View):

   def get(self, request, *args, **kwargs):
       request.session['foo'] = "hi"  

   def post(self, request, *args, **kwargs):
       print(request.session.get('foo', "default value"))

我正在寻找以上输入的以下输出。

               Time Flag    Spread
2016-06-01 09:30:01 new     0
2016-06-01 09:30:04 matched 0.04
2016-06-01 09:30:05 new     0
2016-06-01 09:30:06 new     0
2016-06-01 09:31:02 matched 0.05
2016-06-01 09:31:08 matched 0.04
2016-06-01 09:32:03 matched 0.05
2016-06-01 09:33:09 matched 0.01
2016-06-01 09:34:01 new     0
2016-06-01 09:35:03 matched 0.12
2016-06-01 09:35:04 new     0
2016-06-01 09:35:06 matched 0.08
2016-06-01 09:35:09 matched 0.05

Algo: Time Flag Spread 2016-06-01 09:30:01 new 0 2016-06-01 09:30:04 matched 0.04 2016-06-01 09:30:05 new 0.04 2016-06-01 09:30:06 new 0.04 2016-06-01 09:31:02 matched 0.05 2016-06-01 09:31:08 matched 0.04 2016-06-01 09:32:03 matched 0.05 2016-06-01 09:33:09 matched 0.01 2016-06-01 09:34:01 new 0.01 2016-06-01 09:35:03 matched 0.12 2016-06-01 09:35:04 new 0.12 2016-06-01 09:35:06 matched 0.08 2016-06-01 09:35:09 matched 0.05 行将从上一个Flag == "new"行填充Spread列的值。最后Flag == "match"表示它来自按时间排序的列表。

match

您能否建议简单的Algo Update: If first row/first few rows of data is Flag == "new", then Spread of those rows will remain 0. 实施。

R

1 个答案:

答案 0 :(得分:2)

your_data$Spread = zoo::na.locf(ifelse(
    your_data$Flag == "new", NA, your_data$Spread
))

这是“最后一次观察结果”的直接应用。我假设您的数据已经按照您想要的顺序排序。