vendredi 18 décembre 2020

Loop over rows within ifelse in R

I have a dataframe, dt with two variables as given below. Using the code below, I want to get matrix G.

V1   V2
1   60
1   30
1   38
1   46
2   29
2   35
2   13
2   82
3   100
3   72
3   63
3   45

Code is:

l1 <- seq(1, 3, 1)
G<-matrix(data=0, nrow=3, ncol=3)
for (m in seq_along(l1)){
  for (n in seq_along(l1)){
    G[m,n]=sum(apply(dt,1,function (y) {ifelse(dt$V2[dt$V1==m]<dt$V2[dt$V1==n] ,1,0)}))
  }
}

What I get as G:

     [,1] [,2] [,3]
[1,]    0   24   36
[2,]   24    0   36
[3,]   12   12    0

What I want as G:

     [,1] [,2] [,3]
[1,]    0    5   14
[2,]    5    0   13
[3,]   14   13    0

Basically, for V1=1 we want to compare all values of V2 with all values of V2 for V1= 2 and 3. Repeat the same for V2 and V3.

For V1=1->
( 60 > 29 : loop returns 0,
60 > 35 : loop returns 0,
60 > 13 : loop returns 0,
60 < 82 : loop returns 1,
30 > 29 : loop returns 0,
30 < 35 : loop returns 1,
30 > 13 : loop returns 0,
30 < 82 : loop returns 1,
38 > 29 : loop returns 0,
38 > 35 : loop returns 0,
38 > 13 : loop returns 0,
38 < 82 : loop returns 1,
46 > 29 : loop returns 0,
46 > 35 : loop returns 0,
46 > 13 : loop returns 0,
30 < 82 : loop returns 1)=Sum is 5 (i.e. G[1,2])

How can I revise the code to get the desired output?

Aucun commentaire:

Enregistrer un commentaire