Reputation: 129
Say I have a matrix:
A <- matrix(c(2,4,3,1,5,7), nrow=3, ncol=2)
colnames(A) <- c ("x", "y")
A
x y
[1,] 2 1
[2,] 4 5
[3,] 3 7
Is there a way to access each row of the matrix using a for loop?
What I'm trying to do is total the euclidean distance between each successive point (x,y). So in this example, I would find the total distance between:
(2,1) and (4,5)
(4,5) and (3,7)
So first I would find the distance between each of the two points, ie:
(2,1) and (4,5) => (|4-2|,|5-1|) => (2,4)
(4,5) and (3,7) => (|3-4|,|7-5|) => (1,2)
Then I would turn it into euclidean distance:
(2,4) => sqrt(2^2 + 4^2) => 4.47
(1,2) => sqrt(1^2 + 2^2) => 2.24
And total the distance
4.47 + 2.24 = 6.71
I'm quite confident that if I can access each row of the matrix as a vector, I can easily code this. However, I would love to hear any better ways of doing this.
I was also looking into turning the matrix into a list of lists (ie a list of (x,y) points, where each point is a list of the x and y value), or a list of points (x,y).
I'm not very experienced in programming and I've just started using R, so sorry if I'm not making sense.
Upvotes: 2
Views: 516
Reputation: 3186
You can try the following
for (i in 1:nrow(A))
{
row = A[i,]
% Do something with the row
}
Upvotes: 2
Reputation: 93938
However, I would love to hear any better ways of doing this.
R has built in functions for distance calculations such as dist
, e.g.:
out <- as.matrix(dist(A))
# 1 2 3
#1 0.000000 4.472136 6.082763
#2 4.472136 0.000000 2.236068
#3 6.082763 2.236068 0.000000
You can extract the off-diagonal, which is the values you want, using:
row(out) - col(out)==1
# [,1] [,2] [,3]
#[1,] FALSE FALSE FALSE
#[2,] TRUE FALSE FALSE
#[3,] FALSE TRUE FALSE
Thus:
out[row(out) - col(out)==1]
#[1] 4.472136 2.236068
sum(out[row(out) - col(out)==1])
#[1] 6.708204
Upvotes: 1