如何简化R中的嵌套循环

时间:2018-08-13 01:44:23

标签: r loops 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

}}}

1 个答案:

答案 0 :(得分:0)

您发布的算法不依赖于ndecision,因为它们在简化后被取消了。因此,它可以表示如下:

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)

输出:

  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