# How to add a removed element to the associated sublist after manipulating a list

I have the attached point list and use the following script to cluster the points. The clustering should just be applied to the first three-member of each sublist so I removed the fourth element from each sublist. However, after clustering the fourth member should be added to the associated sublist. How I can do that. https://pastebin.com/SKvFEEQD

A11 = Drop[dataDCMp, None, {4}];
nng = NearestNeighborGraph[A11, 4];
ccmp = ConnectedComponents[nng];

• You could try something like NearestNeighborGraph[dataDCMp, 4, DistanceFunction -> (EuclideanDistance[#1[[;; 3]], #2[[;; 3]]] &)], which may take a while to finish.
– FJRA
Commented Jul 9, 2020 at 2:16
• Mehdi, can you try if Extract[dataDCMp, List /@ ConnectedComponents[IndexGraph@nng]] gives what you need?
– kglr
Commented Jul 9, 2020 at 12:23

One way to do it, not efficient but overhead is small compared to generating the graph.

Import["https://pastebin.com/raw/SKvFEEQD"] // ToExpression;

(* Test on the first 100 to save time *)
assoc = <|Most@# -> Last@#|> & /@ dataDCMp[[1 ;; 100]];
A11 = assoc // Keys
nng = NearestNeighborGraph[A11, 4];
ccmp = ConnectedComponents[nng];

find[key_] := #[key] & /@ assoc // DeleteMissing

Map[Append[#, First@find[#]] &, ccmp, {-2}]

• Thank you Rohit! Your code works but I am getting extra braces. I tried to remove them by flatten function but no proper answer. Do you have any idea what the solution is? Commented Jul 9, 2020 at 5:11
• I found this "a //. {x_List} :> x " from former posts mathematica.stackexchange.com/questions/20180/… and it modified the braces. Thank you again, Rohit! Commented Jul 9, 2020 at 5:16
• The analysis takes too long. Is there any way to do it faster? Commented Jul 9, 2020 at 6:53
• @MehdiEbadi You mean time for NearestNeighborGraph? Commented Jul 9, 2020 at 17:31
• Thank you Rohit! Now I realized that the speed is not too bad. I believe the problem was with my processor. Commented Jul 9, 2020 at 18:03