Creating a triangular matrix from a vector performing sequential operations

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.

+6
source share
2 answers

Using sapply and ifelse :

 sapply(head(vv[vv>0],-1),function(y)ifelse(vv-y>0,vv-y,NA)) 

You loop positive values ​​(you must also remove the last element), then you extract each value from the original vector. I used ifelse to replace negative values.

 # [,1] [,2] [,3] [,4] [,5] # [1,] NA NA NA NA NA # [2,] NA NA NA NA NA # [3,] NA NA NA NA NA # [4,] NA NA NA NA NA # [5,] 1 NA NA NA NA # [6,] NA NA NA NA NA # [7,] 3 2 NA NA NA # [8,] NA NA NA NA NA # [9,] NA NA NA NA NA # [10,] 6 5 3 NA NA # [11,] 7 6 4 1 NA # [12,] 8 7 5 2 1 
+1
source

You can try something like the following (with generous help from @thela)

 res <- outer(aux1, head(aux1[aux1 > 0], -1), `-`) is.na(res) <- res <= 0 # [,1] [,2] [,3] [,4] [,5] # [1,] NA NA NA NA NA # [2,] NA NA NA NA NA # [3,] NA NA NA NA NA # [4,] NA NA NA NA NA # [5,] 1 NA NA NA NA # [6,] NA NA NA NA NA # [7,] 3 2 NA NA NA # [8,] NA NA NA NA NA # [9,] NA NA NA NA NA # [10,] 6 5 3 NA NA # [11,] 7 6 4 1 NA # [12,] 8 7 5 2 1 
+3
source

Source: https://habr.com/ru/post/989159/


All Articles