按组向后填充值 [英] Fill value backwards from occurence by group

查看:42
本文介绍了按组向后填充值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:如何在出现某个值之前向后填充组中的所有行.我不是在尝试使用 zoo na.locf 填写NA或缺少值.在下面的内容中,我希望在每个ID组出现1.00之前,用1.00填充A中的所有先前行,最好使用 dplyr .

Problem: How can I fill backwards all rows in a group before an occurrence of a certain value. I am not trying to fill in NA or missing value using zoo na.locf. In the following I would like to fill all previous rows in A with 1.00 before the 1.00 occurs by each ID group, ideally using dplyr.

输入:

data<- data.frame(ID=c(1,1,1,1,2,2,2,3,3,3,4,4,4,4,4), 
              time=c(1,2,3,4,1,2,3,1,2,3,1,2,3,4,5),
              A=c(0.10,0.25,1,0,0.25,1,0.25,0,1,0.10,1,0.10,0.10,0.10,0.05))
ID time    A
1    1     0.10
1    2     0.25
1    3     1.00
1    4     0.00
2    1     0.25
2    2     1.00
2    3     0.25
3    1     0.00
3    2     1.00
3    3     0.10
4    1     1.00
4    2     0.10
4    3     0.10
4    4     0.10
4    5     0.05

所需的输出:

ID time    A
1    1     1.00
1    2     1.00
1    3     1.00
1    4     0.00
2    1     1.00
2    2     1.00
2    3     0.25
3    1     1.00
3    2     1.00
3    3     0.10
4    1     1.00
4    2     0.10
4    3     0.10
4    4     0.10
4    5     0.05

推荐答案

按ID分组后,您可以检查1的累积总和以及仍低于1(尚未出现)的累积总和,将A值替换为1:

After grouping by ID you can check the cumulative sum of 1's and where it's still below 1 (not yet appeared), replace the A-value with 1:

data %>% 
  group_by(ID) %>% 
  mutate(A = replace(A, cumsum(A == 1) < 1, 1))
# Source: local data frame [15 x 3]
# Groups: ID [4]
# 
# ID  time     A
# <dbl> <dbl> <dbl>
# 1      1     1  1.00
# 2      1     2  1.00
# 3      1     3  1.00
# 4      1     4  0.00
# 5      2     1  1.00
# 6      2     2  1.00
# 7      2     3  0.25
# 8      3     1  1.00
# 9      3     2  1.00
# 10     3     3  0.10
# 11     4     1  1.00
# 12     4     2  0.10
# 13     4     3  0.10
# 14     4     4  0.10
# 15     4     5  0.05

非常相似,您也可以使用 cummax :

Quite similar, you could also use cummax:

data %>% group_by(ID) %>% mutate(A = replace(A, !cummax(A == 1), 1))

这是基本的R方法:

transform(data, A = ave(A, ID, FUN = function(x) replace(x, !cummax(x == 1), 1)))

这篇关于按组向后填充值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆