I was wondering if there is an existing function that can (succinctly) accomplish the following. I'd like to group a column so each group's values are within a certain number (increment_var
) of each other; for example, if increment_var
is 4, then 1, 4, 7, 9 would group into (1, 4) and (7, 9). I wrote a for-loop below that emulates what the function would do. It sort of has the feel of DescTool's RoundTo
and zoo's rollapply
functions. Many thanks!
new_cars <- arrange(mtcars, mpg)
increment_var <- 5
counting_var <- 0
saved_var <- 0
for (i in 1:nrow(new_cars)){
trial_var <- new_cars[i, "mpg"]
if (trial_var - saved_var > increment_var){
counting_var = counting_var + 1
saved_var = trial_var
}
new_cars[i, "new_col"] = counting_var
}
select(new_cars, c(mpg, new_col))
# mpg new_col
# 1 10.4 1
# 2 10.4 1
# 3 13.3 1
# 4 14.3 1
# 5 14.7 1
# 6 15.0 1
# 7 15.2 1
# 8 15.2 1
# 9 15.5 2
# 10 15.8 2
# 11 16.4 2
# 12 17.3 2
# 13 17.8 2
# 14 18.1 2
# 15 18.7 2
# 16 19.2 2
# 17 19.2 2
# 18 19.7 2
# 19 21.0 3
# 20 21.0 3
# 21 21.4 3
# 22 21.4 3
# 23 21.5 3
# 24 22.8 3
# 25 22.8 3
# 26 24.4 3
# 27 26.0 3
# 28 27.3 4
# 29 30.4 4
# 30 30.4 4
# 31 32.4 5
# 32 33.9 5