# is there a way to create this loop in a better way using map?

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.

``````DF <- data.frame(Months_away = -24:24)

DF\$quaters_away <- (DF\$Months_away - (DF\$Months_away > 0)) %/% 3 + (DF\$Months_away > 0)
#>   Months_away quaters_away
#> 1         -24           -8
#> 2         -23           -8
#> 3         -22           -8
#> 4         -21           -7
#> 5         -20           -7
#> 6         -19           -7
tail(DF)
#>    Months_away quaters_away
#> 44          19            7
#> 45          20            7
#> 46          21            7
#> 47          22            8
#> 48          23            8
#> 49          24            8
``````

Created on 2022-03-29 by the reprex package (v2.0.1)

This is brilliant FJCC. I knew there had to be a better way. Thank you

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.