Search code examples
rloopsnested-loops

how to simplify nested loop in R


I have the following code, anyone can advise a different approach to nested loops:

x <- c(1, 2,3)
y <- c(6, 7, 8, 9)

n <- 10

for (i in 1:3) {
  for (j in 1:4) {

  decisions <- rep(0, n)

  for (k in 1:n) {

    ##a predefined function        
    decisions[k] <- pre_defined_funct(x[i], y[j]) 
    percent[i,j] <- sum(decisions)/n

}}}

Solution

  • The algorithm you posted does not depend on n and decision as they are cancelled out after simplification. Hence it can be presented as follows:

    x <- c(1, 2, 3)
    y <- c(6, 7, 8, 9)
    n <- 10
    
    pre_defined_funct <- function(x, y) {
      # stub
      abs(sin(x + y))
    }
    
    prs <- expand.grid(x, y)
    prs$percent <- pre_defined_funct(prs$Var1, prs$Var2)
    library(reshape2)
    dcast(prs, Var2 ~ Var1)
    

    Output:

      Var2         1         2         3
    1    6 0.6569866 0.9893582 0.4121185
    2    7 0.9893582 0.4121185 0.5440211
    3    8 0.4121185 0.5440211 0.9999902
    4    9 0.5440211 0.9999902 0.5365729