id cate result
1 1 yes 1
2 1 yes NA
3 1 no NA
4 2 no NA
5 2 yes 1
6 2 yes NA
7 2 no NA
8 3 no NA
9 3 yes NA
10 3 no NA
11 3 yes 1
12 3 yes NA
13 3 no NA
14 3 yes NA
15 4 yes 1
16 4 yes NA
17 4 yes NA
18 4 no NA
19 4 no NA
I want to fill the value of the result (1) forward up to the first no of the cate variable.
I try it using the code
library(tidyverse)
d2 <- d %>% group_by(id) %>%
fill(result, .direction = 'down')
But the desired output is
id cate result
1 1 yes 1
2 1 yes 1
3 1 no 1
4 2 no NA
5 2 yes 1
6 2 yes 1
7 2 no 1
8 3 no NA
9 3 yes NA
10 3 no NA
11 3 yes 1
12 3 yes 1
13 3 no 1
14 3 yes NA
15 4 yes 1
16 4 yes 1
17 4 yes 1
18 4 no 1
19 4 no NA
I also used the code for the following sample data,
dat <- data.frame(id=c(1,1,1,1,2,2,2,2,2,3,3,3, 4,4,4,4), stat=c('sup','unsup','unsup', 'sup',
'unsup','unsup','unsup','unsup','sup', 'sup','unsup','unsup','sup', 'sup','unsup','unsup'),
ind=c(NA,1,NA,NA,1,1,1,NA,NA,NA,1,NA, NA,NA,1,NA))
and the Expected output
id stat ind
1 1 sup NA
2 1 unsup 1
3 1 unsup 1
4 1 sup 1
5 2 unsup 1
6 2 unsup 1
7 2 unsup 1
8 2 unsup 1
9 2 sup 1
10 3 sup NA
11 3 unsup 1
12 3 unsup 1
13 4 sup NA
14 4 sup NA
15 4 unsup 1
16 4 unsup 1