[R] Assigning categorical values to dates

Rui Barradas ru|pb@rr@d@@ @end|ng |rom @@po@pt
Thu Jul 22 09:49:22 CEST 2021


Hello,

Great function!
Here is a simplified, (hopefully) more general version.


seq_from_group <- function(x){
   x |>
     unique() |>
     sort() |> (\(ranks) match(x, ranks))()
}

date_df |>
   mutate(cycle = seq_from_group(dates))



With ?interaction it works with more than one column.



df2 <- data.frame(
   X = c(rep("a", 4), rep("b", 5)),
   Y = c(rep(1, 2), rep(3,3), rep(2, 4))
)

df2 |>
   mutate(cnt = seq_from_group(interaction(X, Y)))



Hope this helps,

Rui Barradas


Às 07:54 de 22/07/21, Erich Subscriptions escreveu:
> date_df <- tibble(dates = c(rep("2021-07-04", 2), rep("2021-07-25", 3),
> rep("2021-07-18", 4)))
> 
> 
> 
> cycle_from_date <-   function(date,dates){
>    dates |>
>      unique() |>
>      sort() ->
>      ranks
>    match(date,ranks)
> }
> 
> date_df |>
>    mutate(cycle_new=cycle_from_date(dates,dates))
> 
> 
>> On 22.07.2021, at 05:46, N. F. Parsons <nathan.f.parsons using gmail.com> wrote:
>>
>>>> tibble(dates = c(rep("2021-07-04", 2), rep("2021-07-25", 3),
>>>> rep("2021-07-18", 4)))
> 
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list