Formatting print output of for loop

Updated with code that addresses most of my questions.

I have a modest function to generate iterations of a MLE for a population estimate. (I know that iterations are poor form in R, but I am trying to show a nonlinear search procedure in detail, to accompany methods from an Excel spreadsheet).

n <- c(32,54,37,60,41) # number of captures 
R <- c(32,36,6,13,5) # of marked fish returned to the population

fn <- function(x){
  N = 97 #starting value of N
  mle = matrix(0, nrow=x, ncol=8) #per suggestion
  colnames(mle) = c("N","g.N","h.N","N1","g.N1","h.N1","delta.h","corr") #added column names
    
  for (i in 1:x) {
         g.N = prod(1-n/N)
         h.N = N-sum(R)-N*g.N
         N1 = N-1
         g.N1 = prod(1-n/N1)
         h.N1 = N1-sum(R)-N*g.N1
         delta.h = h.N-h.N1
         corr = -h.N/delta.h
   
  #print(c(N,g.N,h.N,N1,g.N1,h.N1,delta.h,corr))#original output
  
  mle[i,] = c(N,g.N,h.N,N1,g.N1,h.N1,delta.h,corr) #per suggestion
      N = N+corr
}
return(mle) #per suggestion
}

fn(5)

This creates the following output

        N        g.N          h.N       N1       g.N1       h.N1   delta.h          corr
[1,] 97.00000 0.04046356 1.075034e+00 96.00000 0.03851149  0.2643856 0.8106486 -1.326141e+00
[2,] 95.67386 0.03788200 4.954192e-02 94.67386 0.03597455 -0.7679654 0.8175073 -6.060119e-02
[3,] 95.61326 0.03776543 2.382189e-03 94.61326 0.03586008 -0.8154412 0.8178234 -2.912841e-03
[4,] 95.61035 0.03775983 1.147664e-04 94.61035 0.03585458 -0.8177238 0.8178386 -1.403289e-04
[5,] 95.61020 0.03775956 5.529592e-06 94.61020 0.03585432 -0.8178338 0.8178393 -6.761220e-06

I would like to cleanup the output, but have not been able to crack the code to put the results in a matrix or data.frame or any format where I can give column titles and adjust the digits, numeric format, etc. in a meaningful manner. I’ve have had limited success with cat and format but have been unable to get them to do precisely what I would like. Any help formatting this as a table, or matrix or data.frame would be appreciated.

Answer

Your function doesn’t actually work for me (what’s n for example). Anyway, you should have something like:

   N<-97 #starting value of N
   m = matrix(0, nrow=5, ncol=7)
   for (i in 1:x) {
     #<snip>

     m[i,] = c(N,g.N,N1,g.N1,h.N1,delta.h,corr)
     N<-N+corr
   }
   return(m)
 }

Leave a Reply

Your email address will not be published. Required fields are marked *