cyague
cyague

Reputation: 885

R from vector/factor to list

My problem is as it follows. I'm dealing with big data graphs using R/igraph.

I need to convert the output of clusters()$membership (i.e a vector), to a list which groups the values.

Example: I have the vector (3,3,3,1,1,4,4) I need a list having the following estructure

l<-list()
l[["3"]]<-c(1,2,3)
l[["4"]]<-c(6,7)
l[["1"]]<-c(4,5)

this is, the structure the output of maximal.cliques() function has

I've tried using lapply on a list of levels, and then using which to find the indexes for a certain value. However this performs really poorly. I'm dealing with data vectors of 180K elements where there may be 60K diffenrent levels.

Upvotes: 2

Views: 838

Answers (2)

Rainer
Rainer

Reputation: 8691

look at split():

> x <- c(3,3,3,1,1,4,4)
> y <- 1:7
> split(y, x)
$`1`
[1] 4 5

$`3`
[1] 1 2 3

$`4`
[1] 6 7


> z <- data.frame(x,y)
> split(z, z$x)
$`1`
  x y
4 1 4
5 1 5

$`3`
  x y
1 3 1
2 3 2
3 3 3

$`4`
  x y
6 4 6
7 4 7

>

Upvotes: 5

Ari B. Friedman
Ari B. Friedman

Reputation: 72769

You can use lapply:

> test.vec <- c(3,3,3,1,1,4,4)
> test.u <- unique(test.vec)
> test.l <- lapply( test.u, function(x, test.vec) which(test.vec==x), test.vec=test.vec )
> names(test.l) <- test.u
> test.l
$`3`
[1] 1 2 3

$`1`
[1] 4 5

$`4`
[1] 6 7

Upvotes: 1

Related Questions