Я не использовал dplyr, но я думаю, что это решает проблему.
NestID <- c(rep("Nest01",5),rep("Nest02",2))
JulianDate <- c(146,149,153,156,160,143,147)
Stage <- c("IB","NG","NG","NG","FL","NG","D")
HostEggs <- c(2,0,0,0,0,1,0)
HostYoung <- c(0,2,2,2,0,1,0)
NSTLAge <- c(NA,1,5,8,NA,5,NA)
NestFate <- c(rep(" ",4),"Fledged"," ","Depredated")
data <- data.frame(NestID,JulianDate,Stage,HostEggs,HostYoung,NSTLAge,NestFate)
InitiationDate <- c()
nests <- names(table(NestID)) #I got the names of the nests
for(i in 1:length(nests)){
p <- min(which(data$NestID==nests[i])) #This is to see the position where the i nest beggings
if(data$Stage[p]=="IB"){
a <- max(which(data$Stage[which(data$NestID==nests[i])]=="IB"))
b <- min(which(data$Stage[which(data$NestID==nests[i])]=="NG"))
InitiationDate[i] <- mean(data$JulianDate[c(a,b)]) - 12
} else if(data$Stage[p]=="NG"){
InitiationDate[i] <- data$JulianDate[p] - data$NSTLAge[p] - 12
}
}
names(InitiationDate) <- nests; InitiationDate