I would like to find the relative distance from a given day of week to another day of week. Assume the following R input of relative differences from day 0, in days:
day <- c(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14)
The domain has a periodicity of one week (thus 7 days). I would like to get the following values:
relativedist <- c(0, 1, 2, 3, 3, 2, 1, 0, 1, 2, 3, 3, 2, 1, 0)
using modulo is a natural first guess, but as expected, not correct - it does not work for circular domains:
day%%4
results in
[1] 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2
I looked at packages circular and circStats, but failed to find an applicable function.
In this case the
pminfunction will give the correct answer but your data is arranged to start and stop at a natural boundary, so you will need to make sure it's as general as you need (it did deliver the same sequence with 1:20 as input as the diffFromNearest function offered by @NickK):The
pminandpmaxfunctions do "side-by-side comparisons of two vectors.This implements the logic in @NickK's procedure using
pminand modulus arithmetic: