Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
项目R:变量“;“深度”;用于循环的时间间隔;一般化_R_For Loop - Fatal编程技术网

项目R:变量“;“深度”;用于循环的时间间隔;一般化

项目R:变量“;“深度”;用于循环的时间间隔;一般化,r,for-loop,R,For Loop,谢谢你帮我解决这个问题。这是一个困扰我很长时间的问题。我觉得我离答案很近了,但还不太清楚。 问题如下: 假设我想要组合n向量的m元素的所有可能组合,并存储乘法的结果。对于2d问题,我需要两个交错的For循环: dim2_Matrix <- matrix(0,nrow=2,ncol=3) for (i in 1:2){ for (j in 1:3){ dim2_Matrix[i,j] <- i*j } } dim2\u Matrix您可以尝试这样的方法 X<-lis

谢谢你帮我解决这个问题。这是一个困扰我很长时间的问题。我觉得我离答案很近了,但还不太清楚。 问题如下:

假设我想要组合n向量的m元素的所有可能组合,并存储乘法的结果。对于2d问题,我需要两个交错的For循环:

dim2_Matrix <- matrix(0,nrow=2,ncol=3)
for (i in 1:2){
  for (j in 1:3){
  dim2_Matrix[i,j] <- i*j
  }
}

dim2\u Matrix您可以尝试这样的方法

X<-list(1:2, 1:3, 1:4)  #one entry for each dimension
Z<-expand.grid(X)
现在,您在
data.frame
中拥有了每个组合,您可以使用apply函数或类似的功能来完成您需要做的事情。例如:

apply(Z,1,prod)

 [1]  1  2  2  4  3  6  2  4  4  8  6 12  3  6  6 12  9 18  4  8  8 16 12 24

您的代码相当于:

dim2\u矩阵=外部(1:2,1:3)

dim3\u矩阵=外部(dim2\u矩阵,1:4)

可概括为:

dim_n_Matrix <- function(n) {
  x <- 1:2
  if (n>1) {for (n in 2:n) {x <- outer(x, 1:(n+1))}} else {x <- matrix(1:2, nrow = 1)}
  return(x)
}

dim\u n\u Matrix看一看
expand.grid()
-这可能会做一些接近你所追求的东西。@Andrie看起来像是齐柏林飞艇成员忍者击败了你:-)也是,谢谢!这个例子(类似Java的伪代码)展示了如何实现一个可变深度的嵌套for循环:已经有一段时间了,但是-是的expand.grid终于完成了任务!为了将列表应用到脚本并正确运行它,我必须查看列表,但现在它可以工作了。谢谢
   Var1 Var2 Var3
1     1    1    1
2     2    1    1
3     1    2    1
4     2    2    1
5     1    3    1
6     2    3    1
7     1    1    2
8     2    1    2
9     1    2    2
10    2    2    2 
11    1    3    2
12    2    3    2
13    1    1    3
14    2    1    3
15    1    2    3
16    2    2    3
17    1    3    3
18    2    3    3
19    1    1    4
20    2    1    4
21    1    2    4
22    2    2    4
23    1    3    4
24    2    3    4
apply(Z,1,prod)

 [1]  1  2  2  4  3  6  2  4  4  8  6 12  3  6  6 12  9 18  4  8  8 16 12 24
dim_n_Matrix <- function(n) {
  x <- 1:2
  if (n>1) {for (n in 2:n) {x <- outer(x, 1:(n+1))}} else {x <- matrix(1:2, nrow = 1)}
  return(x)
}