[R] sparse vectors

Dimitris Rizopoulos d.rizopoulos at erasmusmc.nl
Tue Sep 8 15:27:06 CEST 2009


one simple way could be:

sparse.vec <- function (..., fun = sum) {
     lis <- list(...)
     values <- unlist(lapply(lis, "[[", "value"))
     inds <- factor(unlist(lapply(lis, "[[", "index")))
     out <- tapply(values, inds, FUN = fun)
     list(index = as.numeric(levels(inds)), values = out)
}

a <- list(index = c(20, 30, 100000000), value = c(2.2, 3.3, 4.4))
b <- list(index = c(3, 30), value = c(0.1, 0.1))
sparse.vec(a, b)
sparse.vec(a, b, fun = prod)
sparse.vec(a, b, fun = function(x) Reduce("-", x))


I hope it helps.

Best,
Dimitris


Robin Hankin wrote:
> Hi
> 
> I deal with long vectors almost all of whose elements are zero.
> Typically, the length will be ~5e7 with ~100 nonzero elements.
> 
> I want to deal with these objects using a sort of sparse
> vector.
> 
> The problem is that I want to be able to 'add' two such
> vectors.
> Toy problem follows.  Suppose I have two such objects, 'a' and 'b':
> 
> 
> 
>  > a
> $index
> [1]    20   30 100000000
> 
> $val
> [1] 2.2 3.3 4.4
> 
> 
> 
>  > b
> $index
> [1]   3  30
> 
> $val
> [1] 0.1 0.1
> 
>  >
> 
> 
> What I want is the "sum" of these:
> 
>  > AplusB
> $index
> [1]    3   20   30 100000000
> 
> $val
> [1]  0.1 2.2 3.4 4.4
> 
>  >
> 
> 
> See how the value for index=30 (being common to both) is 3.4
> (=3.3+0.1).   What's the best R idiom to achieve this?
> 
> 
> 

-- 
Dimitris Rizopoulos
Assistant Professor
Department of Biostatistics
Erasmus University Medical Center

Address: PO Box 2040, 3000 CA Rotterdam, the Netherlands
Tel: +31/(0)10/7043478
Fax: +31/(0)10/7043014




More information about the R-help mailing list