Fill in the value in the opposite direction by groups

Problem: . How can I fill back all the lines in a group until a certain value appears. I am not trying to fill in an NA or missing value using zoo na.locf. In the following case, I would like to fill in all the previous lines from 1.00 before 1.00 will be executed by each group of identifiers, ideally using dplyr.

Input:

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

Desired conclusion:

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
+2
source share
2 answers

After grouping by ID, you can check the total amount of 1 and where it is still below 1 (has not yet appeared), replace the value of A 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

In exactly the same way, you can also use cummax:

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

And here's the basic R approach:

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

data.table. 'data.frame' 'data.table' (setDT(data)), , 'A' 1, , i (:=) 'A' 1

library(data.table)
setDT(data)[data[, .I[seq_len(which(A==1))], ID]$V1, A := 1][]
#   ID time    A
# 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

ave base R

data$A[with(data, ave(A==1, ID, FUN = cumsum)<1)] <- 1
+3

All Articles