我还有另外一个关于那里的精彩头脑的问题(这个网站很容易让人上瘾)。将for循环的结果赋值给一个空矩阵
我正在矩阵上运行一些模拟,并且为此嵌套了循环。第一个创建一个向量,每次循环循环时增加1。嵌套循环通过随机化矢量,将其附加到矩阵并计算新矩阵上的一些简单属性来运行仿真。 (例如,我使用的属性在仿真中不会改变,但实际上我需要仿真来了解随机向量的影响。)嵌套循环运行100次仿真,最终我只需要这些模拟的列方式。
下面是一些示例代码:
property<-function(mat){ #where mat is a matrix
a=sum(mat)
b=sum(colMeans(mat))
c=mean(mat)
d=sum(rowMeans(mat))
e=nrow(mat)*ncol(mat)
answer=list(a,b,c,d,e)
return(answer)
}
x=matrix(c(1,0,1,0, 0,1,1,0, 0,0,0,1, 1,0,0,0, 1,0,0,1), byrow=T, nrow=5, ncol=4)
obj=matrix(nrow=100,ncol=5,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
I.vec=append(a,b) #append these two for the I vector
for (j in 1:100){
I.vec2=sample(I.vec,replace=FALSE) #randomize I vector
temp=rbind(x,I.vec2)
prop<-property(temp)
obj[[j]]<-prop
}
write.table(colMeans(obj), 'myfile.csv', quote = FALSE, sep = ',', row.names = FALSE)
}
我遇到的问题是如何与嵌套循环的结果空对象矩阵填写。 obj最终成为主要NAs的一个向量,所以很明显我没有正确地分配结果。我希望每个周期道具的行添加到OBJ,但如果我尝试
obj[j,]<-prop
[R告诉我,没有对矩阵标数不正确。
非常感谢您的帮助!
EDITS: 好了,所以这里再下面的答案改进代码:
property<-function(mat){ #where mat is a matrix
a=sum(mat)
b=sum(colMeans(mat))
f=mean(mat)
d=sum(rowMeans(mat))
e=nrow(mat)*ncol(mat)
answer=c(a,b,f,d,e)
return(answer)
}
x=matrix(c(1,0,1,0, 0,1,1,0, 0,0,0,1, 1,0,0,0, 1,0,0,1), byrow=T, nrow=5, ncol=4)
obj<-data.frame(a=0,b=0,f=0,d=0,e=0) #create an empty dataframe to dump results into
obj2<-data.frame(a=0,b=0,f=0,d=0,e=0)
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
I.vec=append(a,b) #append these two for the I vector
for (j in 1:100){
I.vec2=sample(I.vec,replace=FALSE) #randomize I vector
temp=rbind(x,I.vec2)
obj[j,]<-property(temp)
}
obj2[i,]<-colMeans(obj)
write.table(obj2, 'myfile.csv', quote = FALSE,
sep = ',', row.names = FALSE, col.names=F, append=T)
}
然而,这仍然是出问题的,因为myfile的应该只有四排(一个用于每列x),但实际上有10行,有些重复。有任何想法吗?
太棒了!谢谢你的所有建议。 – Laura
我可以通过添加“append = T”来解决覆盖问题。 obj现在可以正常工作,但生成write.table的文件仍然只有一列。我通过创建第二个空数据框,以obj的colMeans作为行来解决此问题,然后将其写入一个csv文件。 – Laura