This loop works. But i'm wondering if there's another way to do it using map. Months away is a vector of integers taking on positive and negative values. I am creating a new variable called quarters away that basically bins the months away variable, so that if months away is > 1 and <= 3 it will equal 1, and so on.
I am wondering whether there is a more clever way to write this loop
j <- 1
df$quarters_away <- NA_real_
for (i in seq(1,24,3)) {
df$quarters_away[df$months_away >= i & df$months_away < (i+3)] <- j
df$quarters_away[df$months_away > -i-3 & df$months_away <= -i] <- -j
j <- j + 1
}
How about no loop at all? I did some adjusting with DF$Months_away > 0 because you want Months_away == 1 to return Quarters_away of 1. The comparison > returns zero if it is FALSE and one if it is TRUE. The %/% operator is for integer division. It returns the whole number of times one numer goes into another.