
This function transforms a cyclic variable (e.g., hour of the day, day of the week, month of the year) into its cosine representation. This transformation ensures that machine learning models respect the cyclical nature of such features.
cyclical_cos(x, period)
A numeric vector representing the cosine-transformed values.
A numeric vector representing a cyclic variable (e.g., hour, month, day).
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.
This function applies the transformation:
# Convert hours of the day to cosine encoding
hours <- 0:23
cyclical_cos(hours, 24)
# Convert months of the year to cosine encoding
months <- 1:12
cyclical_cos(months, 12)
Run the code above in your browser using DataLab