I have created the following data.table in R:
> DT
ID num code
1: b 1 C1
2: b 1 C1
3: b 1 C1
4: b 1 C1
5: b 1
6: b 3
7: b 3 C1
8: a 3 C2
9: a 3 C3
10: a 3 C3
11: a 3
12: c 4 C3
where empty values are empty strings "". I then run the instruction
res <- DT[, .(agg_code = unique(code)[!(code == "")]), .(ID, num)]
which results in
> res
ID num agg_code
1: b 1 C1
2: b 1
3: b 1 <NA>
4: b 1 <NA>
5: b 3 C1
6: a 3 C2
7: a 3 C3
8: a 3
9: c 4 C3
My question is: what is this command actually doing? I understand that it is grouping by ID and num, I don't understand how unique(code) and [!(code == "")] are working. They are deleting some rows, but they are also keep some "" and creating some <NA>. What is happening here?
For completeness, DT is created by
DT = data.table(
ID = c("b","b","b", "b","b", "b","b","a","a","a","a", "c"),
num = c(1,1,1,1,1,3,3,3,3,3,3,4),
code = c("C1", "C1","C1","C1", "", "","C1", "C2", "C3", "C3","", "C3")
)