lundi 24 mai 2021

Translate matrix algebra code from VB to R

For a project, I am trying to replicate/rewrite the following Visual Basic code from a case study so I can run it in R.

For j=1 to N
    For I=1 to M
        While I>j
            If b(I,j) c=P then
                a(I,j)=l else
                if b(1, j)<= [P+ (l-P ) /21 then
                    a(I,j)=3 else
                    a(1, j)=O
                end if
            end if
        wend
        while Icj
            if a(I,j)=l then
                a(j,i)=l else
                if a(I,j)=3 then
                    a(j,I)=O else
                    a( j ,I) =3
                end if
             end if
        wend
    next
next

The goal is to compare the values b(j,I) from matrix B(M,N) and fill matrix A(M,N) with either 0,1 or 3. It should represent the results of a football game.

This is what I got so far:

M <- 3
N <- 3

A <- matrix(0,M,N)

B <- matrix(sample(0:4,25, replace=TRUE),nrow=M, ncol=N)

for (i in 1:nrow(B)) {
for (j in 1:ncol(B)) {
  while (i > j) {
    if (B[i,j] > B[j,i]) {
      A[i,j] = 3 & A[j,i] = 0
    }
    if (B[i,j] < B[j,i]) {
      A[i,j] = 0 & A[j,i] = 3
    }
    else {
      A[i,j] = 1 & A[j,i] = 1
    }
  }
    }
      }

I would really appreciate any help or tips!

Aucun commentaire:

Enregistrer un commentaire