Reputation: 103
I have 3 sets of list called minDist. Each list has three columns hence it has three groups (1, 2 & 3).
minDist:
[[1]]
[,1] [,2] [,3]
[1,] 1.000000 9.055385 9.000000
[2,] 0.000000 9.000000 9.055385
[3,] 1.414214 8.062258 8.000000
[4,] 1.000000 8.000000 8.062258
[5,] 9.055385 1.000000 0.000000
[6,] 9.000000 0.000000 1.000000
[7,] 10.049876 1.414214 1.000000
[8,] 10.000000 1.000000 1.414214
[9,] 5.000000 5.830952 6.403124
[10,] 5.656854 6.403124 7.071068
[[2]]
[,1] [,2] [,3]
[1,] 10.000000 10.049876 9.055385
[2,] 10.049876 10.000000 9.000000
[3,] 9.000000 9.055385 8.062258
[4,] 9.055385 9.000000 8.000000
[5,] 1.000000 1.414214 1.000000
[6,] 1.414214 1.000000 0.000000
[7,] 0.000000 1.000000 1.414214
[8,] 1.000000 0.000000 1.000000
[9,] 7.211103 6.708204 5.830952
[10,] 7.810250 7.211103 6.403124
[[3]]
[,1] [,2] [,3]
[1,] 0.000000 1.000000 9.055385
[2,] 1.000000 1.414214 9.000000
[3,] 1.000000 0.000000 8.062258
[4,] 1.414214 1.000000 8.000000
[5,] 9.000000 8.000000 1.000000
[6,] 9.055385 8.062258 0.000000
[7,] 10.000000 9.000000 1.414214
[8,] 10.049876 9.055385 1.000000
[9,] 5.656854 5.000000 5.830952
[10,] 6.403124 5.830952 6.403124
I want to find out which row belongs to the same groups. For example, List 1:
[1] 1 1 1 1 3 2 3 2 1 1
Meaning row 1,2,3,4,9,and 10 belongs to group 1, row 6 and 8 belongs to group 2 row 5 and 7 belongs to group 3.
If I only have one list, this is how I try to do the grouping:
grouping <- apply(minDist, 1, which.min)
How can I get the answers for all the three list using loops?
Upvotes: 1
Views: 2805
Reputation: 24480
Try:
lapply(minDist, function(x) max.col(-x))
Don't use the highly inefficient apply(x,1,which.min)
; use max.col
instead, which returns for each row of a matrix the index of the maximum value (if you want the minimum, you just find the maximum of the opposite of x
).
Upvotes: 6
Reputation: 887118
We can use lapply
to loop over the list
elements and then do the apply
lapply(minDist, function(x) apply(x, 1, which.min))
Upvotes: 2