Search code examples
rvectorizationcluster-analysis

How could I convert a list of cluster labels into a vector of indices?


The toy example I'm currently working with is a list object in R that looks like this:

[[1]] 4 6

[[2]] 1 5

[[3]] 2 8

[[4]] 3 7

And we can interpret this as a clustering where observations 4 and 6 are in cluster 1, observations 1 and 5 are in cluster 2, etc. But I want to get these cluster labels in index form, so I want to convert the list to the vector (2, 3, 4, 1, 2, 1, 4, 3). In practice I will have much more than 8 observations. Does anyone know of a quick way to do this?


Solution

  • x = list(c(4, 6), c(1, 5), c(2, 8), c(3, 7))
    i = rep(seq_along(x), lengths(x))
    i[order(unlist(x))]
    # [1] 2 3 4 1 2 1 4 3