我有一个数据框,其中基本上有一个 ID#、一个年份和一个状态代码。这是一个例子:
> 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
我想根据 ID# 的状态将第 4 列 (df$def
) 添加为二进制文件,但是,一旦状态为“d”,我就需要它来执行尽管状态可能变为“c”,但剩余年数。我可以编写简单的 IF 语句,使“c”为 0,“d”为 1,但我无法计算向前的日期。
我希望决赛 table 看起来像这样:
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
感谢您的帮助!
最佳答案
你可以使用:
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
或者对于更大的数据集,您可以使用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
或者你可以使用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
关于r - 基于 R 中日期的匹配值的 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26407266/