替换此列表中的循环

问题描述 投票:1回答:2

我正在尝试比较列表中同一列的2到2行,为此,我嵌套了循环,但是花很长时间才能给我输出。我读了有关Apply函数或ifelse来代替de循环的文章,但是,我不知道该怎么做。我的代码是这样的:

 #Var1 and var2 are vectors with integers from 0 to 30.
 V=data.frame("name1"=c(var1),"name2"=c(var2))
 ns=0;nx=0;nd=0;
 for (a in c(1:(length(var1)-1))){
  for(b in c((a+1):length(var1))){ #I use this trying to compare every element of the column.
    if (abs(V[a,1]-V[b,1])<=0.5 | abs(V[a,2]-V[b,2])<=0.5)
    {
      nx=nx+1;
    } 
    else {
      if (V[a,1]>V[b,1]) {x=1}
      else {x=0}  
      if (V[a,2]>V[b,2]) {y=1}
      else {y=0}    
      if (x+y==0 | x+y==2) {ns=ns+1}
      else {nd=nd+1}  
    }
  }
}
r loops for-loop optimization
2个回答
1
投票

这是我的变体:

set.seed(42)
n <- 1000
V <- data.frame(name1=sample.int(30, n, repl=TRUE), name2=sample.int(30, n, repl=TRUE))
nsxd <- function(V1, V2) {
  ns=0; nx=0; nd=0
  for (a in 1:(length(V1)-1)) {
    for(b in (a+1):length(V1)) { #I use this trying to compare every element of the column.
      if (abs(V1[a]-V1[b])<=0.5 | abs(V2[a]-V2[b])<=0.5) nx <- nx+1 else {
        x <- V1[a]>V1[b]
        y <- V2[a]>V2[b]
        if (x+y==0 | x+y==2) {ns=ns+1} else {nd=nd+1}  
      }
    }
  }
  return(c(ns=ns, nx=nx, nd=nd))
}
nsxd(V[, 1], V[, 2])

0
投票

这希望使用combn加快速度:

var1 <- 0:4
ns=0;nx=0;nd=0;

# replaces a and b part of the loop
ind <- t(combn(var1+1, 2))
# if you have a very large vector, look into:
#ind <- RcppAlgos::comboGeneral(var1 + 1, 2)


# replaces a and b part of the loop
# ind <- t(combn(1000, 2))
# if you have a very large vector, look into:
ind <- RcppAlgos::comboGeneral(var1+1, 2)

#coercion to matrix for speed
mat <- as.matrix(V)

#replaces first if then statement
comp1 <- rowSums(abs(mat[ind[, 1], ] - mat[ind[, 2], ]) <= 0.5)!=0
nx <- sum(comp1)

#initial work for the x + y assignments
comp2 <- rowSums(mat[ind[, 1], ] > mat[ind[, 2], ])[!comp1]

ns <- sum(comp2 != 1)
nd <- length(comp2) - ns  
© www.soinside.com 2019 - 2024. All rights reserved.