简体   繁体   English

R中的嵌套双循环

[英]nested double loop in R

mat <- matrix(0,ncol=6, nrow=100)
d=c(1,2,4,8,16,32)
for(i in 1:6)
{
  for(j in d)
  {
    mat[,i]=rep(j,100)
  }
}
mat

I should get a 100 x 6 matrix with columns of 1,2,4,8,16,32. 我应该得到一个100 x 6的矩阵,其中的列分别为1,2,4,8,16,32。 However, I simply get rows of 32 in every column. 但是,我只获得每列32行。 Does anyone have any idea how I can fix this. 有谁知道我该如何解决这个问题。 I do want to use loops, even if its one loop that's fine. 我确实想使用循环,即使它的一个循环很好也是如此。

Based on your description: 100 rows x 6 columns, column 1 = value 1...column 6 = value 32, this should generate what you want. 根据您的描述:100行x 6列,列1 =值1 ...列6 =值32,这将生成您想要的内容。

matrix(data = rep(c(1,2,4,8,16,32), each = 100), 
       nrow = 100, 
       ncol = 6)

The answer from @neilfws is more elegant. @neilfws的答案更加优雅。 If you are committed to using a loop for some reason you can do this 如果由于某种原因承诺使用循环,则可以执行此操作

mat <- matrix(0,ncol=6, nrow=100)
d=c(1,2,4,8,16,32)
for(i in 1:6)
{
  j <- d[i]

    mat[,i]=rep(j,100)

}
mat

The issue is that you were looping through all of d for each column. 问题是您要遍历每一列的所有d。

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

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