0

I have a data fram looks like:

the data

I want to add a dummy column based on id group and acp which if acq == 1, then the later year in that group will have a dummy value with 1. something like this :

desired output

im trying to doing this in r. i tried with double for loop or dply but all fails. Any help will be appreciated.

f.lechleitner
  • 3,554
  • 1
  • 17
  • 35
peteraa
  • 11
  • 1
  • Please use `dput` to show the input dataset and also expected output (instead of images) You can try `library(dplyr); df1 %>% group_by(id) %>% mutate(Post = lag(cummax(Acq), default = 0)` – akrun Feb 19 '18 at 07:07
  • Welcome to StackOverflow! Please read the info about [how to ask a good question](http://stackoverflow.com/help/how-to-ask) and how to give a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610). This will make it much easier for others to help you. – Jaap Feb 19 '18 at 08:02

1 Answers1

0

After grouping by 'id', we can use cummax and take the lag of it

library(dplyr)
df1 %>% 
   group_by(id) %>%
   mutate(Post = lag(cummax(Acq), default = 0))
# A tibble: 7 x 4
# Groups: id [2]
#     id  Year   Acq  Post
#  <int> <int> <dbl> <dbl>
#1     1  2008  0     0   
#2     1  2009  0     0   
#3     1  2010  0     0   
#4     2  2008  0     0   
#5     2  2009  1.00  0   
#6     2  2010  0     1.00
#7     2  2011  0     1.00

data

df1 <- data.frame(id = rep(1:2, c(3, 4)), Year = c(2008:2010, 2008:2011),
           Acq = c(0, 0, 0, 0, 1, 0, 0))
akrun
  • 874,273
  • 37
  • 540
  • 662