Dear R Users, I created a function which returns a value every time it's run (A simplified toy example is attached on this mail).
For example spat(a,b,c,d) # run the first time and it gives you ans1= 10, perm=1 ; run the second time and gives you ans2= 7, perm=2 etc I store both the result and the iteration on a matrix called vector with columns:1==ans, column2==permutation The rule I want to implement is: compare between ans1 and ans2. If ans1>ans2, keep both ans1 and ans2. if ans1<ans2, drop the whole row of the second permutation (that is drop both ans2 and perm2 but continue counting all permutations). Re-run the function for the 3rd time and repeat comparison between the value of the last run and the current value obtained. Return matrix ans with the saved ans and their permutations and another full matrix with all results including the dropped ans and their permutation numbers. I need to repeat this process 1000 times but I am getting stuck below. See attached R code. The code below works only for the first 6 permutations. suppose I want 1000 permutations, where do I keep the loop? Example: Not a perfect code though it somehow works: testx<-function(perm){ optA<-c() #while(perm<=2){ for (k in 1:perm){ #repeat { optA[k]<-sample(1:1000,1,replace=TRUE) perm[k]<-k } mat2<-as.matrix(cbind(optA=optA,perm=perm)) result<-mat2 lenm<-nrow(result) if(result[1,1]<=result[2,1]) result<-result[1,] return(list(mat2=mat2,result=result)) #} if(perm>2){ mat2<-as.matrix(cbind(optA=optA,perm=perm)) result<-mat2 lenm<-nrow(result) if(result[1,1]<=result[2,1]) result<-result[1,] if(result[lenm-1,1]<=result[lenm,1]) result<-result[-lenm,] if(result[(lenm-2),1]<=result[(lenm-1),1]) result<-result[-(lenm-1),] if(result[(lenm-3),1]<=result[(lenm-2),1]) result<-result[-(lenm-2),] if(result[(lenm-4),1]<=result[(lenm-3),1]) result<-result[-(lenm-3),] if(result[(lenm-5),1]<=result[(lenm-4),1]) result<-result[-(lenm-4),] return(list(mat2=mat2,result=result)) } } ## Now calling my function below: >testx(perm=6) $mat2 optA perm [1,] 272 1 [2,] 858 2 [3,] 834 3 [4,] 862 4 [5,] 650 5 [6,] 405 6 $result optA perm 272 1 > testx(perm=2) $mat2 optA perm [1,] 398 1 [2,] 816 2 $result optA perm 398 1 [[alternative HTML version deleted]] ______________________________________________ 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.