I am writing a for loop for my dataset "identified" in which each iteration is dependent on the previous iterations. I want it so
- If no previous iterations have the same value in male.year as the current iteration does in male.previousyear, malerematingstatusb = 0
- If any previous iteration has the same value in "male.year" as the current iteration does in "male.previousyear" AND that iteration also has the same value in "pair" as the current iteration does, "malerematingstatusb" = 1
- If any previous iteration has the same value in "male.year" as the current iteration does in "male.previousyear" AND that iteration does not have the same value in "pair" as the current iteration does AND that iteration the layingdate is <= the value in the "last.seen.female" column of the current iteration, malerematingstatusb = 2
- If any previous iteration has the same value in "male.year" as the current iteration does in "male.previousyear" AND that iteration does not have the same value in "pair" as the current iteration does AND that iteration the layingdate is > the value in the "last.seen.female" column of the current iteration, malerematingstatusb = 3
This is the code I am working with:
for(i in 1:length(identified$year)) {
ifelse(
(!(identified$male.previousyear[i] %in% identified$male.year[1:i-1])),
identified$malerematingstatusb[i] <- 0,
ifelse(
(nrow(subset((subset(identified, identified$male.previousyear[i] == identified$male.year[1:i-1],)), identified$pair[i] == identified$pair[1:i-1],)) > 0),
identified$malerematingstatusb[i] <- 1,
ifelse(
(nrow(subset((subset((subset(identified, identified$male.previousyear[i] == identified$male.year[1:i-1],)), identified$pair[i] != identified$pair[1:i-1],)), identified$layingdate[i] <= identified$last.seen.female[1:i-1],)) > 0),
identified$malerematingstatusb[i] <- 2,
ifelse(
(nrow(subset((subset((subset(identified, identified$male.previousyear[i] == identified$male.year[1:i-1],)), identified$pair[i] != identified$pair[1:i-1],)), identified$layingdate[i] > identified$last.seen.female[1:i-1],)) > 0),
identified$malerematingstatusb[i] <- 3,
identified$malerematingstatusb[i] <- NA)))) }
It all works, except that all the values which should be 3 are also 2. This makes me think it is a problem in trying to get the code to look at previous iterations values being <= the current iteration values. I have checked and both "layingdate" and "last.seen.female" are in numeric form. Any help?
Aucun commentaire:
Enregistrer un commentaire