I am trying to solve the following problem.
Suppose I have the following vector:
aux1<-c(0,0,0,4,5,0,7,0,0,10,11,12) , where the numbers represent the line number.
I want to calculate the distance between the various elements of this vector, fixing the first component, then the second, etc.
If the element is zero, I do not want to count it, so instead of it I put NA. The result I want should look like this:
NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA 1 NA NA NA NA NA NA NA NA NA 3 2 NA NA NA NA NA NA NA NA NA NA NA NA NA 6 5 3 NA NA 7 6 4 1 8 7 5 2 1
In the first column, I have a difference between the first non-zero element and all other elements, i.e. matrix [5,1] = 5-4 = 1 and matrix [12,1] = 12-4 = 8. Matrix [7,2] = 7-5 = 2, where 5 is the second element in the vector, not equal to zero . Note that the Matrix [10,3] = 10-7 = 3, where 7 is the third element, not equal to zero, but the seventh element in my vector.
I tried to do this in a loop. My current code is as follows:
M=matrix(nrow=N-1, ncol=N-1)) for (i in 1:N-1){ for (j in 1:N-1){ if(j<=i) next else if(aux1[j]>0) M[j,i]=aux1[j]-aux1[i] else M[j,i]=0 } }
Unfortunately. I could not solve my problem. Any help would be greatly appreciated.