我有另一个问题,那里的聪明人(这个网站是如此上瘾).
我在矩阵上运行一些模拟,为此目的我已经嵌套了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)
}
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是如何使用嵌套循环的结果填充空对象矩阵.obj最终成为大多数NA的向量,所以很明显我没有正确地分配结果.我希望每个循环都向obj添加一行道具,但是如果我尝试的话
obj[j,]<-prop
Run Code Online (Sandbox Code Playgroud)
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)
}
Run Code Online (Sandbox Code Playgroud)
但是,这仍然是一个小故障,因为myfile应该只有四行(每列x一行),但实际上有10行,有些行重复.有任何想法吗?
您的property函数正在返回一个列表。如果你想将数字存储在矩阵中,你应该让它返回一个数字向量:
property <- function(mat)
{
....
c(a, b, c, d, e) # probably a good idea to rename your "c" variable
}
Run Code Online (Sandbox Code Playgroud)
或者,不要定义obj为矩阵,而是将其设为 a data.frame(这在概念上更有意义,因为每一列代表不同的数量)。
obj <- data.frame(a=0, b=0, c=0, ...)
for(i in 1:ncol(x))
....
obj[j, ] <- property(temp)
Run Code Online (Sandbox Code Playgroud)
最后,请注意,您的调用write.table将覆盖 的内容myfile.csv,因此它将包含的唯一输出是 i 的最后一次迭代的结果。