【发布时间】:2011-10-22 21:58:41
【问题描述】:
我还有一个问题要问那些聪明的人(这个网站太让人上瘾了)。
我正在一个矩阵上运行一些模拟,并为此目的嵌套了 for 循环。第一个创建一个向量,每次循环循环时都会增加一个。嵌套循环通过随机化向量、将其附加到矩阵并计算新矩阵的一些简单属性来运行模拟。 (例如,我使用了在模拟中不会改变的属性,但实际上我需要模拟才能很好地了解随机向量的影响。)嵌套循环运行 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 最终成为主要是 NA 的向量,因此很明显我没有正确分配结果。我希望每个循环都为obj添加一行prop,但是如果我尝试
obj[j,]<-prop
R 告诉我矩阵上的下标数量不正确。
非常感谢您的帮助!
编辑: 好的,下面是改进后的代码:
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 行,有些是重复的。有什么想法吗?
【问题讨论】: