mathematical.coffee
mathematical.coffee

Reputation: 56905

Index a vector by a sparseVector

I'm using the Matrix package of R. I have a sparseVector

index.map <- sparseVector(x=1:3, i=c(10, 33, 50), length=50)

and some values to look up (an ordinary vector)

values <- runif(3)

Now I wish to extract elements of values going through index.map e.g.

values[index.map[33]] # should return values[2]

I get the error

Error in values[index.map[33]] : invalid subscript type 'S4'

presumably because R does not know how to subset the numeric values by a sparseVector. I can coerce index.map to an integer to do the lookup:

values[as(index.map[33], 'integer')] == values[2] # TRUE

but this is rather verbose for such a simple operation, and I've got to do the coercion every time I use index.map - I'm not sure how efficient this is.

Is there a different way to do this indexing? or is this the only option?


I thought perhaps converting values to a sparseVector might help, as perhaps the Matrix package would know how to subset a sparseVector by another sparseVector, but it does not:

as(values, 'sparseVector')[index.map[33]]
# Error in as(values, "sparseVector")[index.map[33]] : 
#   object of type 'S4' is not subsettable

Update @x (thanks @AleksandrVoitov!) doesn't seem to work all the time. For example

values[index.map[c(10, 10, 33)]@x]

is returning values[c(1, 2, 1)] rather than values[c(1, 1, 2)], while using as(.., 'integer') on index.map[c(10, 10, 33)] works as expected. Perhaps @x is not meant to be a 'public' way to interact with a sparseVector?

Upvotes: 0

Views: 111

Answers (1)

Aleksandr
Aleksandr

Reputation: 1914

Try subseting with:

values[index.map[33]@x]

This would give you

values[2]=0.608075

Upvotes: 1

Related Questions