Hello, I'm having two similar problems with for loop and I would appreciate any help or comment.
I want to use "for loop" to calculate series of initial values for an optimization problem. But some initial values have my function quit due to problems like calculating the inverse of singular matrices. I don't want to make my program check determinants and skip it if it is very small. My program stopping for certain iterations is okay but my problem is that the whole for loop is ended from there and it does not move to the next iteration. So the rest of the initial values are never tried. Here is a simple example: mat.inv <- function(theta){ mat1 <- matrix( theta, nr=2) inv <- solve(mat1) res <- theta[1]+inv[1,1] res } for (i in 1:7){ theta4 <- i theta.vec <- c(1,2,2,theta4) theta.res <- mat.inv(theta.vec) write.table(theta.res, paste("result",i,".txt",sep="")) } It stops when i=4. I need to try other values. How would I get it to simply move on to the next iteration :i=5,6,7 without checking determinants? Another similar problem that I have is that I have thousands of txt files and want to use a for loop to read them into R. The file names are consecutive but some of them are missing: For example, they are "result1.txt", "result2.txt", "result3.txt", "result5.txt"... When I use for loop to read it, it gets an error at "result4.txt" so that "result5.txt"... are not read. I attached an example program here. Could anyone help me? I appreciate your time in advance. Kyeongmi #create dataset name for (i in 1:6){ assign(paste("newname",i,sep=""), paste("result",i,".txt",sep="")) } ls() #read data if there are files with the name: "result1.txt", "result2.txt", "result3.txt", "result5.txt". for (i in 1:6){ assign( paste("r",i,sep=""), read.table(get(paste("newname",i,sep="")), header=T) ) } # It stops at "result3.txt" so that "result5.txt"... are not read. ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.