【发布时间】:2011-10-13 02:59:49
【问题描述】:
我在这里有嵌套 for 循环的代码。我想接收的输出是嵌套循环产生的矩阵列的均值矩阵。因此,内部循环应该运行 1000 次随机向量模拟,并且每次运行一个函数。这本身就可以正常工作,并将输出吐到 R 中。但我想将嵌套循环的输出保存到一个对象(1000 行和 11 列的矩阵),然后只打印该矩阵的 colMeans,到由外循环执行。
我认为问题在于我将内部循环的结果分配给 obj 矩阵的步骤。我已经尝试了 obj[i,]、obj[i]、obj[[i]] 等的所有变体,但没有成功。 R 告诉我它是一个只有一维的对象。
x=ACexp
obj=matrix(nrow=1000,ncol=11,byrow=T) #create an empty matrix to dump results into
for(i in 1:ncol(x)){ #nested for loops
a=rep(1,times=i) #repeat 1 for 1:# columns in x
b=rep(0,times=(ncol(x)-length(a))) #have the rest of the vector be 0
Inv=append(a,b) #append these two for the Inv vector
for (i in 1:1000){ #run this vector through the simulations
Inv2=sample(Inv,replace=FALSE) #randomize interactions
temp2=rbind(x,Inv2)
obj[i]<-property(temp2) #print results to obj matrix
}
print.table(colMeans(obj)) #get colMeans and print to excel file
}
有什么办法可以解决这个问题吗?
【问题讨论】: