基于R中匹配条件的最后一行值的填充

基于R中匹配条件的最后一行值的填充,r,match,R,Match,我有以下输入数据 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:

我有以下输入数据

               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
我要从上面的输入下面的输出

               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
算法:带有
标志==“new”
的行将填充上次
标志==“match”
行中
排列
列的值。Last
match
表示它来自时间排序列表

Algo Update: If first row/first few rows of data is Flag == "new",
then Spread of those rows will remain 0.
您能为同样的问题建议简单的
R
实现吗

Update: Updated first row of input and output data as well as Algo,
to reflect updated query based on primary reply from @Gregor.

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

只是为了更新我的原始查询:有时,如果第一行数据具有标志==“new”。那么对于那一行,我希望Spread=0保持不变。您可以建议对原始代码进行扩展吗?在
zoo::na.locf
中设置
na.rm=FALSE
,然后使用
your_data$Spread[is.na(your_data$Spread)]=0
。或者将
zoo::na.locf
替换为
zoo::na.fill(,fill=list(0,“extend”,“extend”)
)。
your_data$Spread = zoo::na.locf(ifelse(
    your_data$Flag == "new", NA, your_data$Spread
))