[R] how to store a vector of vectors

Sarah Goslee sarah.goslee at gmail.com
Sat Nov 13 15:48:59 CET 2010


You are assuming that R is using row-major order
for recycling elements, when in fact it is using column-
major order.

It doesn't show up in the first case, because all the
elements of x are identical

> x <- c(1,1,1)
> matrix(x, nrow=2, ncol=3)
     [,1] [,2] [,3]
[1,]    1    1    1
[2,]    1    1    1
> x <- c(1,1,2)
> matrix(x, nrow=2, ncol=3)
     [,1] [,2] [,3]
[1,]    1    2    1
[2,]    1    1    2

Here's one possible fix. But note that the guts of dist() are
implemented in C, so it will be faster than your solution for
large matrices, regardless of the extra calculations.
(And just to be picky, dist() returns an object of class dist.)

> norm <- function(x, y) {
+ x <- matrix(x, nrow=nrow(y), ncol=ncol(y), byrow=TRUE)
+ sqrt( rowSums( (x-y)^2 ) )
+ }
>
>
> y <- matrix(
+      c(  1,1,1,
+           2,3,4), nrow=2, byrow=TRUE)
> x <- c(1,1,1)
> norm(x, y)
[1] 0.000000 3.741657
>
> y <- matrix( c(1,1,2,1,2,2), nrow=2, byrow=TRUE )
> x <- c(1,1,2)
> norm(x,y)
[1] 0 1
>
>

Sarah


On Sat, Nov 13, 2010 at 9:17 AM, Alexx Hardt <mikrowelle1234 at gmx.de> wrote:
> Am 13.11.2010 14:39, schrieb Sarah Goslee:
>>
>> I at least would need to see an actual example of your code to
>> be able to answer your question.
>>
>
> My function:
>
> norm <- function(x,y){
>  sqrt( rowSums( (x-y)^2 ) )
> }
>
> y <- matrix(
>      c(  1,1,1,
>           2,3,4), nrow=2, byrow=TRUE)
> x <- c(1,1,1)
>
> Here, norm(x,y) does work. But here:
>
> y <- matrix( c(1,1,2,1,2,2), nrow=2, byrow=TRUE )
> x <- c(1,1,2)
> norm(x,y)
>
> it produces weird numbers:
>
> [1] 1.414214 1.00000
>
> which is sqrt(2) and 1. I have no idea what gets mixed up here :-(
>
>> But why not just use dist() and take the appropriate column of the
>> resultant matrix?
>>
>> mydist<- function(x, amat) {
>> # x is the single variable as a vector
>> # amat is the remaining variables as rows
>> alldist<- dist(rbind(x, amat))
>> as.matrix(alldist)[-1,1]
>> }
>>
>
> dist returned a vector for me, and I didn't know how to extract the proper
> elements.
> Also, I'm kind of OCD about wasted computations, which would be the
> distances between elements of y :-)
>
> Thanks,
>  Alex
>

-- 
Sarah Goslee
http://www.functionaldiversity.org



More information about the R-help mailing list