繁体   English   中英

R中for循环的替代方案

[英]alternative of for loop in R


cell_support_xyz <- function(level, zero)
{
  for(i in 1:level[1]){
    for(j in 1:level[2]){
      for(k in 1:level[3]){
        cat("cell (", i, ", ", j, ", ", k,") --> support set = (", 
            +!(i == zero[1]), ", ", +!(j == zero[2]), ", ", +!(k == zero[3]), ")\n", sep = "")
        
      }      
    }
  }
}


#Example 1
l<-c(2,3,2)
z<-c(1,1,1)
> cell_support_xyz(l,z)

cell (1, 1, 1) --> support set = (0, 0, 0)
cell (1, 1, 2) --> support set = (0, 0, 1)
cell (1, 2, 1) --> support set = (0, 1, 0)
cell (1, 2, 2) --> support set = (0, 1, 1)
cell (1, 3, 1) --> support set = (0, 1, 0)
cell (1, 3, 2) --> support set = (0, 1, 1)
cell (2, 1, 1) --> support set = (1, 0, 0)
cell (2, 1, 2) --> support set = (1, 0, 1)
cell (2, 2, 1) --> support set = (1, 1, 0)
cell (2, 2, 2) --> support set = (1, 1, 1)
cell (2, 3, 1) --> support set = (1, 1, 0)
cell (2, 3, 2) --> support set = (1, 1, 1)

上面的代码工作得很好。 但我想避免for循环。 这里我使用了 3 个 for 循环(因为两个参数向量的长度都是 3)。 如果向量的长度增加或减少,函数将不起作用(我需要相应地调整 for 循环); 这就是为什么我想用一些适用于任何长度的有效替代方法替换 for 循环。 有什么建议吗?

一种删除for循环并使解决方案对于任何长度输入足够灵活的方法。

我们使用expand.grid创建所有可能的level组合,并使用apply rowwise 创建要打印的字符串。

cell_support_xyz <- function(level, zero) {
  tmp <- do.call(expand.grid, lapply(level, seq))
  abc <- apply(tmp, 1, function(x) 
               cat(sprintf('cell (%s) --> support set = (%s)\n', 
                   toString(x), toString(+(x != zero)))))
}

l<-c(2,3,2)
z<-c(1,1,1)

cell_support_xyz(l, z)
#cell (1, 1, 1) --> support set = (0, 0, 0)
#cell (2, 1, 1) --> support set = (1, 0, 0)
#cell (1, 2, 1) --> support set = (0, 1, 0)
#cell (2, 2, 1) --> support set = (1, 1, 0)
#cell (1, 3, 1) --> support set = (0, 1, 0)
#cell (2, 3, 1) --> support set = (1, 1, 0)
#cell (1, 1, 2) --> support set = (0, 0, 1)
#cell (2, 1, 2) --> support set = (1, 0, 1)
#cell (1, 2, 2) --> support set = (0, 1, 1)
#cell (2, 2, 2) --> support set = (1, 1, 1)
#cell (1, 3, 2) --> support set = (0, 1, 1)
#cell (2, 3, 2) --> support set = (1, 1, 1)

您可以分两步完成:

l<-c(2,3,2)
z<-c(1,1,1)

cells <- expand.grid(lapply(l, seq))

t(apply(cells, 1, function(x) 1L*!(x == z)))

cells包含所有组合。 如果顺序很重要,您可以简单地重新排序:

cells <- dplyr::arrange(cells, Var1, Var2, Var3)

然后,对于每一行( apply(,1,) ),您可以使用==已经矢量化来将整行与整个z向量进行比较。

乘以1L使其成为整数,与+相同。

暂无
暂无

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

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