I have the following data.table*:
dt <- data.table(
LEFT = letters[c(1:5, 10:12)],
SELF = letters[c(2:6, 11:13)],
RIGHT = letters[c(3:7, 12:14)]
)
dt <- dt[sample(nrow(dt)), ]
dt[]
# LEFT SELF RIGHT
# 1: e f g
# 2: d e f
# 3: j k l
# 4: c d e
# 5: l m n
# 6: b c d
# 7: a b c
# 8: k l m
LEFT and RIGHT indicate the neighbors of SELF. I'd like to index the table such that I group and order contiguous neighbors. An ideal output could look something like this:
dt_out[]
# LEFT SELF RIGHT RUN ORDER
# 1: e f g 1 5
# 2: d e f 1 4
# 3: j k l 2 1
# 4: c d e 1 3
# 5: l m n 2 3
# 6: b c d 1 2
# 7: a b c 1 1
# 8: k l m 2 2
run_1 <- dt_out[RUN == 1][order(ORDER)][["SELF"]]
run_1
# [1] "b" "c" "d" "e" "f"
I am tempted to write a function to apply to SELF to identify where LEFT == SELF == RIGHT, but I think this is the wrong avenue to go down given data.table's order-by-group capabilities.
*in reality, my data.table has 1.9M observations and is not ordered in any meaningful way.