R: how to store vector vectors

I am trying to write a function to determine the Euclidean distance between x (one point) and y (the set of n points). How to pass function y? So far I have used a matrix like this:

[,1] [,2] [,3] [1,] 0 2 1 [2,] 1 1 1 

To pass the points (0,2,1) and (1,1,1) of this function.

However, when I pass x as a regular (column) vector, the two variables do not match in the function. I either have to transpose x or y, or save the vector of vectors in another way.

My question is: what is the standard way to save more than one vector in R? (my matrix y)
Is it just my y transposed or maybe a list or dataframe?

+4
source share
2 answers

There is no standard way, so you just have to choose the most efficient one, which, on the other hand, depends on how this vector of vectors looks right after creation (it is better to avoid any transformation that is not necessary) and on the speed of the function itself.

I believe that a data.frame with columns x, y and z should be a pretty good choice; the distance function will be quite simple and fast:

 d<-function(x,y) sqrt((y$xx[1])^2+(y$yx[2])^2+(y$zx[3])^2) 
+1
source

The apply function with margin = 1 seems the most obvious:

 > x [,1] [,2] [,3] [1,] 0 2 1 [2,] 1 1 1 > apply(x , 1, function(z) crossprod(z, 1:length(z) ) ) [1] 7 6 > 2*2+1*3 [1] 7 > 1*1+2*1+3*1 [1] 6 

So, if you need distances, then the square root of cross-producing differences at the selected point seems to work:

 > apply(x , 1, function(z) sqrt(sum(crossprod(z -c(0,2,2), zc(0,2,2) ) ) ) ) [1] 1.000000 1.732051 
0
source

All Articles