Sorting the result of a combn on a data.table

Hello experts,

I am trying to to achieve an ascending order sorting of combn result in a data frame.

My data is following

library(data.table)
library(dplyr,warn.conflicts = FALSE)
library(tidyr)
c1<-c(19,20)
c2<-c(5,6)
c3<-c(-49,-50)	
df_1<-data.table(c1,c2,c3)
df_2 <- df_1 %>% rowwise() %>% 
    mutate(COMB=list(combn(c_across(c1:c3),2,simplify = FALSE))) %>%
    unnest(cols = COMB) %>% 
    unnest(cols=COMB)%>%group_by(c1,c2,c3)%>%mutate(CAT=paste("Result", ((row_number() - 1) %/% 2)+1))

which gives me this

| c1 | c2 | c3   | COMB | CAT      |
|----|----|------|------|----------|
| 19 | 5  | \-49 | 19   | Result 1 |
| 19 | 5  | \-49 | 5    | Result 1 |
| 19 | 5  | \-49 | 19   | Result 2 |
| 19 | 5  | \-49 | \-49 | Result 2 |
| 19 | 5  | \-49 | 5    | Result 3 |
| 19 | 5  | \-49 | \-49 | Result 3 |
| 20 | 6  | \-50 | 20   | Result 1 |
| 20 | 6  | \-50 | 6    | Result 1 |
| 20 | 6  | \-50 | 20   | Result 2 |
| 20 | 6  | \-50 | \-50 | Result 2 |
| 20 | 6  | \-50 | 6    | Result 3 |
| 20 | 6  | \-50 | \-50 | Result 3 |

But my desired output is this

| c1 | c2 | c3   | COMB | CAT      |
|----|----|------|------|----------|
| 19 | 5  | -49 | 5    | Result 1 |
| 19 | 5  | -49 | 19   | Result 1 |
| 19 | 5  | -49 | -49 | Result 2 |
| 19 | 5  | -49 | 19   | Result 2 |
| 19 | 5  | -49 | -49 | Result 3 |
| 19 | 5  | -49 | 5    | Result 3 |
| 20 | 6  | -50 | 6    | Result 1 |
| 20 | 6  | -50 | 20   | Result 1 |
| 20 | 6  | -50 | -50 | Result 2 |
| 20 | 6  | -50 | 20   | Result 2 |
| 20 | 6  | -50 | -50 | Result 3 |
| 20 | 6  | -50 | 6    | Result 3 |

Thank you in advance.

(df_3 <- dplyr::arrange(df_2,
                 c1,c2,c3,CAT,COMB))
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.

Superb !!! Thanks for your time.