If for consistent date based values ββin R
I have a dataframe where I essentially have an ID #, year, and status code. Here's an example:
> df <- data.frame(ID=c(100,100,100,102,102,102),
Year=c(2010,2011,2012,2010,2011,2012),
Status=c("c","d","d","d","c","c"))
> df
ID Year Status
1 100 2010 c
2 100 2011 d
3 100 2012 d
4 102 2010 d
5 102 2011 c
6 102 2012 c
I want to add the 4th column ( df$def
) as a binary based on the status ID #, however, once the status is "d" I need to be able to carry over the remaining years despite the status potentially changing to "c". I can write a simple IF statement to have 0 for "c" and 1 for "d", but I am having trouble factoring forward dates.
I would like the final table to look like this:
df
ID Year Status Def
1 100 2010 c 0
2 100 2011 d 1
3 100 2012 d 1
4 102 2010 d 1
5 102 2011 c 1
6 102 2012 c 1
Thanks for the help!
+3
source to share
3 answers
You can use:
within(df, {def<- ave(Status=='d', ID, FUN=cumsum);def[def>1] <- 1 })
# ID Year Status def
#1 100 2010 c 0
#2 100 2011 d 1
#3 100 2012 d 1
#4 102 2010 d 1
#5 102 2011 c 1
#6 102 2012 c 1
Or for a larger dataset, you can use data.table
library(data.table)
setDT(df)[, Def:=cumsum(Status=='d'), by=ID][ Def>1, Def:=1][]
# ID Year Status Def
#1: 100 2010 c 0
#2: 100 2011 d 1
#3: 100 2012 d 1
#4: 102 2010 d 1
#5: 102 2011 c 1
#6: 102 2012 c 1
Or you can use split
res <- unsplit(lapply(split(df, df$ID), function(x) {
indx <- which(x$Status=='d')
x$Def <- 0
if(length(indx)>0){
indx1 <- indx[1]
x$Def[indx1:nrow(x)] <- 1
}
x}), df$ID)
res
# ID Year Status Def
#1 100 2010 c 0
#2 100 2011 d 1
#3 100 2012 d 1
#4 102 2010 d 1
#5 102 2011 c 1
#6 102 2012 c 1
+1
source to share