How can I delete certain rows according to two columns which have symmetricl values in data.table in R?

后端 未结 4 1483
粉色の甜心
粉色の甜心 2021-01-22 04:45

For example, I have a table as follows:

DT <- data.table(
  A = c(1,1,1,2,2,2,3,3,3), 
  B = c(1,2,3,1,2,3,1,2,3),
  key = \"A\"
)

I wand to

4条回答
  •  旧巷少年郎
    2021-01-22 05:33

    Another option:

    DT[, g := paste(B, A, sep="_")][A < B, g := paste(A, B, sep="_")][!duplicated(g), !"g"]
    
       A B
    1: 1 1
    2: 1 2
    3: 1 3
    4: 2 2
    5: 2 3
    6: 3 3
    

    So ...

    1. make a grouping variable as A + B,
    2. flip the order to B + A on subset A < B or A > B
    3. dedupe on the grouping variable

    The last step could alternately be unique(DT, by="g").

提交回复
热议问题