Dear all,

I know there have been various questions posted over the years about loops but I'm afraid that I'm still stuck.  I am using Windows XP and R 2.9.2.
I am generating some data using the multivariate normal distribution (within the 'mnormt' package). [The numerical values of sanad and covmat are not important.]
> datamat <- rmnorm(n=1500,mean=c(mean(sanad[,1]),mean(sanad[,2]),mean(sanad[,3])),varcov=covmat)

The middle column of 'datamat' is simulated data for age.  Obviously some of the simulated values are not going to be sensible.  Therefore I'd like to set up a function that looks at each row of 'datamat' and if the value for the middle column is <5 or >86 then the whole row is replaced by another imputed row.  Of course, the problem is that the imputed value for age may be outside my acceptable range too.

If there a way to set up a loop such that it keeps checking each row until  the values are within the range?

So far I have the following but this doesn't repeat the process.
ctstrunk <- function(data)
                {
                for(i in 1:nrow(data)){
                if(data[i,2]<5)
                data[i,]<-rmnorm(n=1,mean=c(mean(sanad[,1]),mean(sanad[,2]),mean(sanad[,3])),varcov=covmat)
                if(data[i,2]>86)
                data[i,]<-rmnorm(n=1,mean=c(mean(sanad[,1]),mean(sanad[,2]),mean(sanad[,3])),varcov=covmat)
                }
                return(data)
                }

I thought of perhaps a repeat loop such as the following but this loop never stops...
ctstrunk <- function(data)
                {
                repeat{
for(i in 1:nrow(data)){
                if(data[i,2]<5)
                data[i,]<-rmnorm(n=1,mean=c(mean(sanad[,1]),mean(sanad[,2]),mean(sanad[,3])),varcov=covmat)
                if(data[i,2]>5){break}
                }
                repeat{
for(i in 1:nrow(data)){
                if(data[i,2]>86)
                data[i,]<-rmnorm(n=1,mean=c(mean(sanad[,1]),mean(sanad[,2]),mean(sanad[,3])),varcov=covmat)
                if(data[i,2]<86){break}
                }
                return(data)
                }

I have also tried a while loop but again, the function didn't stop
ctstrunk <- function(data)
                {
                for(i in 1:nrow(data)){
                while(data[i,2]<5) data[i,]<-rmnorm(n=1,mean=c(mean(sanad[,1]),mean(sanad[,2]),mean(sanad[,3])),varcov=covmat)
                while(data[i,2]>86) data[i,]<-rmnorm(n=1,mean=c(mean(sanad[,1]),mean(sanad[,2]),mean(sanad[,3])),varcov=covmat)
                }
                return(data)
                }

Many thanks for any assistance you can offer.

Kind regards,
Laura

Laura Bonnett
Research Assistant
Department of Biostatistics
University of Liverpool

Telephone: 0151 7944059
Email: L.J.Bonnett@liv.ac.uk


	[[alternative HTML version deleted]]

