cyclical_sin: Convert a Cyclical Variable to Sine Representation
Description
This function transforms a cyclic variable (e.g., hour of the day, day of the week, month of the year)
into its sine representation. This transformation ensures that machine learning models respect
the cyclical nature of such features.
Usage
cyclical_sin(x, period)
Value
A numeric vector representing the sine-transformed values.
Arguments
x
A numeric vector representing a cyclic variable (e.g., hour, month, day).
period
A positive numeric scalar representing the period of the cycle.
For example, use 24 for hours of the day, 7 for days of the week, and 12 for months.
Details
This function applies the transformation:
$$sin(2 * \pi * x / period)$$
This encoding ensures that the first and last values in the cycle are smoothly connected.
# Convert hours of the day to sine encodinghours <- 0:23cyclical_sin(hours, 24)
# Convert months of the year to sine encodingmonths <- 1:12cyclical_sin(months, 12)