[R] Matrix manipulation in for loop
clips10
m.mcquillan at lancaster.ac.uk
Mon May 16 11:50:33 CEST 2011
Hi all,
I have a problem with getting my code to do what I want!
This is the code I have:
create.means.one.size<-function(nsample,var,nboot){
mat.x<-matrix(0,nrow=nboot,ncol=nsample)
for(i in 1:nboot){
mat.x[i,]<-sample(var,nsample,replace=T)
}
mean.mat<-rep(0,nboot)
for(i in 1:nboot){
mean.mat[i]<-mean(mat.x[i,])
}
sd.mean<-sd(mean.mat)
return(mean.mat)
}
where nsample here is a scalar.
Then this is where I have the problem
create.all.means<-function(nsample,var,nboot){
MEANS<-matrix(0,nrow=nboot,ncol=length(nsample))
for(j in nsample){
MEANS[,]<-create.means.one.size(j,var,nboot)
}
return(A=list("MEANS"=MEANS,"nsample"=nsample,"std.dev"=sd(MEANS)))
}
here nsample is a vector of the different sample sizes I want. This function
should first create an empty matrix MEANS then it loops through the possible
values of nsample each time it calls create means.one.size() and puts the
output into the appropriate column of means.
this function outputs the matrix MEANS and the vector nsample - both as
part of a list
However, the vector nsample could be c(1,3,5) but I want the outputs to go
into columns 1, 2 and 3 rather than 1,3,5 (which I'm not even sure would
work anyway!) Any help would be great!
If I leave the code as it is and use the vector
data<-c(1,2,3)
Then
create.all.means(c(1,2),data,5)
gives
$MEANS
[,1] [,2]
[1,] 2.5 2.5
[2,] 1.0 1.0
[3,] 2.0 2.0
[4,] 2.0 2.0
[5,] 2.0 2.0
$nsample
[1] 1 2
$std.dev1] 0.5477226 0.5477226[
which obviously isn't correct :(
--
View this message in context: http://r.789695.n4.nabble.com/Matrix-manipulation-in-for-loop-tp3525849p3525849.html
Sent from the R help mailing list archive at Nabble.com.
More information about the R-help
mailing list