简体   繁体   English

循环遍历 R 中 ifelse 中的行

[英]Loop over rows within ifelse in R

I have a dataframe, dt with two variables as given below.我有一个 dataframe, dt 有两个变量,如下所示。 Using the code below, I want to get matrix G.使用下面的代码,我想得到矩阵 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:我得到的 G:

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

What I want as G:我想要的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.基本上,对于 V1=1,我们希望将 V2 的所有值与 V1=2 和 3 的所有 V2 值进行比较。对 V2 和 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?如何修改代码以获得所需的 output?

I would solve it using combination of combn and outer :我会结合使用combnouter来解决它:

#Unique V1 values
vec <- unique(df$V1)
#Count <= valies
val <- combn(vec, 2, function(x) 
  sum(outer(df$V2[df$V1 == x[1]], df$V2[df$V1 == x[2]], `<=`)))
val
#[1]  5 14 13

#Create an empty matrix
mat <- matrix(0,length(vec), length(vec))
#Fill upper and lower triangle of the matrix. 
mat[upper.tri(mat)] <- val
mat[lower.tri(mat)] <- val
mat

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM