Home > other >  Invalid argument to unary operator (on character column)
Invalid argument to unary operator (on character column)

Time:10-26

Say I have the below df

df <- data.table(group_id = c(1,1,2,2)
                 , week_no = c('2019-01', '2019-02', '2019-03', '2019-04')
                 ); df

   group_id week_no
1:        1 2019-01
2:        1 2019-02
3:        2 2019-03
4:        2 2019-04

And a grouped frank works fine:

df[, dummy := frankv(week_no), group_id]; df

   group_id week_no dummy
1:        1 2019-01     1
2:        1 2019-02     2
3:        2 2019-03     1
4:        2 2019-04     2

However, if I wanted to rank in descending order:

df[, dummy := frankv(-date), group_id]; df

I get the error:

Error in -date : invalid argument to unary operator

I suppose it is to do with column week_no's class being character. Is there a way around this other than ranking date in ascending order, then ranking the dummy column in descending order? Thank you.

CodePudding user response:

Is this what you are looking for?

library(data.table)

df[, dummy := frankv(week_no, order = -1L), group_id][]
#>    group_id week_no dummy
#> 1:        1 2019-01     2
#> 2:        1 2019-02     1
#> 3:        2 2019-03     2
#> 4:        2 2019-04     1

Created on 2021-10-25 by the reprex package (v0.3.0)

  • Related