Skip to content
Prev 75544 / 398502 Next

Re-sort list of vectors

Here is one possible and ugly hack. 

 mylist  <- list("1"=c(a=1, b=2, c=3), "2"=c(d=4, b=5, e=6))

 myvec   <- unlist( mylist )
   1.a 1.b 1.c 2.d 2.b 2.e 
     1   2   3   4   5   6 
 
 mymat   <- sapply( strsplit( names(myvec) , split="\\." ) , c )
      [,1] [,2] [,3] [,4] [,5] [,6]
  [1,] "1"  "1"  "1"  "2"  "2"  "2" 
  [2,] "a"  "b"  "c"  "d"  "b"  "e" 


 tmp     <- data.frame( "main"=mymat[2,], 
                        "sub"=mymat[ 1,], "value"=myvec )
     main sub value
 1.a    a   1     1
 1.b    b   1     2
 1.c    c   1     3
 2.d    d   2     4
 2.b    b   2     5
 2.e    e   2     6

I would be quite happy with at this point to loop through the rows and
insert this element by element into MySQL. This may be inefficient for
large datasets. Otherwise I can create this into a matrix with NAs.


So here is my ugly hack to get the list format that you desire. 

 tmp2    <- data.frame( "main"=tmp$main, 
              "elements"=paste('"', tmp$sub, '"=', tmp$value, sep="") )

 newlist <- tapply( noquote(as.character(tmp2$elements)), tmp2$main, c )

 newlist
 $a
 [1] "1"=1

 $b
 [1] "1"=2 "2"=5

 $c
 [1] "1"=3

 $d
 [1] "2"=4

 $e
 [1] "2"=6

I am sure someone will come up with a shorter and neater solution.

Regards, Adai
On Mon, 2005-08-15 at 19:09 +0200, Jan Hummel wrote: