[R-sig-Geo] obtaining row indexes from a list of column indexes

Roger Bivand Roger.Bivand at nhh.no
Wed Nov 17 21:05:44 CET 2010


On Wed, 17 Nov 2010, Edzer Pebesma wrote:

> List,
>
> given an arbitrary n x m boolean matrix, say
>
>      [,1]  [,2]  [,3]  [,4]  [,5]
> [1,] FALSE FALSE FALSE FALSE FALSE
> [2,] FALSE FALSE  TRUE FALSE FALSE
> [3,] FALSE FALSE FALSE FALSE FALSE
> [4,] FALSE FALSE FALSE  TRUE  TRUE
>
> I have the TRUE entries (indexes) of each column, in a list
>
> [[1]]
> integer(0)
>
> [[2]]
> integer(0)
>
> [[3]]
> [1] 2
>
> [[4]]
> [1] 4
>
> [[5]]
> [1] 4
>
> How can I, from this list, efficiently obtain the TRUE entries of each
> row, in this case
>
> [[1]]
> integer(0)
>
> [[2]]
> [1] 3
>
> [[3]]
> integer(0)
>
> [[4]]
> [1] 4 5
>
> without constructing the n x m boolean matrix?

Use sparse matrices?

library(Matrix)
i <- c(2, 4, 4)
j <- c(3, 4, 5)
x <- c(TRUE, TRUE, TRUE)
M <- sparseMatrix(i, j, x=x)
here <- which(M, arr.ind=TRUE)
split(here[,2], here[,1])

is almost there, what remains is to insert the empty list elements.

Roger


>

-- 
Roger Bivand
Economic Geography Section, Department of Economics, Norwegian School of
Economics and Business Administration, Helleveien 30, N-5045 Bergen,
Norway. voice: +47 55 95 93 55; fax +47 55 95 95 43
e-mail: Roger.Bivand at nhh.no



More information about the R-sig-Geo mailing list