Hi Slavek - two answers in one
library(tidyverse)
library(lubridate)
#>
#> Attaching package: 'lubridate'
#> The following object is masked from 'package:base':
#>
#> date
df <- data.frame(
VitalCode = c(223L, 221L, 221L, 221L, 2415L),
Accountnum = as.factor(c("A", "A", "A", "A", "B")),
RoDate = dmy_hm(c("17/12/2012 00:00", "05/03/2013 00:00",
"15/03/2013 00:00",
"10/06/2014 00:00",
"26/06/2019 00:00")),
MOTFlag =c("NO", "NO", "NO", "YES", "NO"))
# for ranks by full date
df %>%
mutate(newvar = factor(rank(RoDate))) ->
df
glimpse(df)
#> Observations: 5
#> Variables: 5
#> $ VitalCode <int> 223, 221, 221, 221, 2415
#> $ Accountnum <fct> A, A, A, A, B
#> $ RoDate <dttm> 2012-12-17, 2013-03-05, 2013-03-15, 2014-06-10, 20...
#> $ MOTFlag <fct> NO, NO, NO, YES, NO
#> $ newvar <fct> 1, 2, 3, 4, 5
# for integer factors by year
df %>%
mutate(newvar = as.integer(factor(year(RoDate)))) ->
df
glimpse(df)
#> Observations: 5
#> Variables: 5
#> $ VitalCode <int> 223, 221, 221, 221, 2415
#> $ Accountnum <fct> A, A, A, A, B
#> $ RoDate <dttm> 2012-12-17, 2013-03-05, 2013-03-15, 2014-06-10, 20...
#> $ MOTFlag <fct> NO, NO, NO, YES, NO
#> $ newvar <int> 1, 2, 2, 3, 4