从R中的双for循环打印对象
这里有嵌套for循环的代码。我希望接收的输出是嵌套循环生成的矩阵列的平均值矩阵。因此,内部循环应该运行随机向量的1000次模拟,每次运行一个函数。这本身就可以很好地工作,并将输出放入R。但是我想将嵌套循环的输出保存到一个对象(一个1000行11列的矩阵),然后只打印该矩阵的colMeans,由外部循环执行 我认为问题在于我将内环的结果分配给obj矩阵的步骤。我尝试过obj[I],obj[I],obj[[I]]等的每一种变体,但都没有成功。R告诉我它是一个只有一维的物体从R中的双for循环打印对象,r,loops,printing,for-loop,R,Loops,Printing,For Loop,这里有嵌套for循环的代码。我希望接收的输出是嵌套循环生成的矩阵列的平均值矩阵。因此,内部循环应该运行随机向量的1000次模拟,每次运行一个函数。这本身就可以很好地工作,并将输出放入R。但是我想将嵌套循环的输出保存到一个对象(一个1000行11列的矩阵),然后只打印该矩阵的colMeans,由外部循环执行 我认为问题在于我将内环的结果分配给obj矩阵的步骤。我尝试过obj[I],obj[I],obj[[I]]等的每一种变体,但都没有成功。R告诉我它是一个只有一维的物体 x=ACexp obj=
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
}
x=ACexp
obj=矩阵(nrow=1000,ncol=11,byrow=T)#创建一个空矩阵以将结果转储到
for(i in 1:ncol(x)){#嵌套for循环
a=rep(1,times=i)#对1重复1:#x中的列
b=rep(0,乘以=(ncol(x)-长度(a))#让向量的其余部分为0
Inv=append(a,b)#为Inv向量追加这两个
对于(1:1000中的i){#在模拟中运行这个向量
Inv2=样本(Inv,替换=假)#随机化交互作用
temp2=rbind(x,Inv2)
obj[i]当整个矩阵被修改时,您会重复将其打印到屏幕上,但您的注释是“打印到excel文件”。我猜您实际上是想将数据保存到文件中。请删除print.table命令,并在循环完成后使用write.table()
(我的首选选项…请参见?write.table以选择您喜欢的选项)由于您的代码不可复制,我们无法完全说出您想要的内容。但是,我猜该属性返回了一个数字,您希望将其放在obj
矩阵的正确行/列位置,您将其称为obj[row,col]
。但这样做会有问题,因为您的两个循环都使用相同的索引i
。也许类似的方法适合您
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
Inv <- rep(c(1,0), times=c(i, ncol(x)-i)) #repeat 1 for 1:# columns in x, then 0's
for (j in 1:nrow(obj)){ #run this vector through the simulations
Inv2 <- sample(Inv,replace=FALSE) #randomize interactions
temp2 <- rbind(x,Inv2)
obj[j,i] <- property(temp2) #save results in obj matrix
}
}
write.csv(colMeans(obj), 'myFile.csv') #get colMeans and print to csv file
obj
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
Inv <- rep(c(1,0), times=c(i, ncol(x)-i)) #repeat 1 for 1:# columns in x, then 0's
for (j in 1:nrow(obj)){ #run this vector through the simulations
Inv2 <- sample(Inv,replace=FALSE) #randomize interactions
temp2 <- rbind(x,Inv2)
obj[j,i] <- property(temp2) #save results in obj matrix
}
}
write.csv(colMeans(obj), 'myFile.csv') #get colMeans and print to csv file