Q:

R create a list of character vectors

I'm trying to process an adjacency matrix into a list of communities,
the output should be a list of vectors (of type character)
For example
l1[1] = c("a","b","c")
l1[2] = c("d")
l1[3] = c("e","f")

I'm trying to achieve this in a for loop:
l1=vector("list")

for(kn in 1:nrow(adjFinal)){
  temp = c()

  for(tm in 1:ncol(adjFinal))
    {
    if(adjFinal[kn,tm]==1)
      temp=c(temp,colnames(adjFinal)[tm])
  }

  l1[kn] = temp
}

But I keep getting warning of "number of items to replace is not a multiple of replacement length" , and a list of 3 vectors of length 1
like:
l1[1] = "a"
l1[2] = "d"
l1[3] = "e"

Update:
this is the adjFinal:
3 x 6 sparse Matrix of class "dgCMatrix"
  a b c d e f
b 1 1 1 . . .
d . . . 1 . .
e . . . . 1 1

and dput(adjFinal):
new("dgCMatrix"
    , i = c(0L, 0L, 0L, 1L, 2L, 2L)
    , p = 0:6
    , Dim = c(3L, 6L)
    , Dimnames = list(c("b", "d", "e"), c("a", "b", "c", "d", "e", "f"))
    , x = c(1, 1, 1, 1, 1, 1)
    )

Thank you in advance.

A:

You can try:
apply(adjFinal,1,function(x) colnames(adjFinal)[which(x==1)])
#$b
#[1] "a" "b" "c"
#$d
#[1] "d"
#$e
#[1] "e" "f"

Consider that you have a sparse matrix and so the above might be inefficient if you have a large matrix, because apply will coerce the sparse matrix to a regular one. To avoid this, you can also try:
adj2<-as(adjFinal,"dgTMatrix")
split(colnames(adjFinal)[adj2@j+1],adj2@i)

which will get the same result, but more efficiently.

