[R] how to store a vector of vectors

Alexx Hardt mikrowelle1234 at gmx.de
Sat Nov 13 15:17:50 CET 2010


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



More information about the R-help mailing list