I am trying to plot histogram from the R output which is not a data frame. Below are my codes and the output.
x <- replicate(1000,
{y <- rpois(200, 1)
{lambda0 <- 1
for(i in 1:1)
{
if( i == 1 ) cat( sprintf("%15s %15s %15s %15s\n", "LogL", "Score", "Information", "New Estimate"))
logL <- sum((-lambda0) + y*(log(lambda0)))
score <- sum((y/lambda0)-1)
information <- sum(y/(lambda0)^2)
lambda1 <- lambda0 + score/information
cat( sprintf("%15.4f %15.4f %15.4f %15.5f\n", logL, score, information, lambda1))
lambda0 <- lambda1
}
}
})
Below is my output
I'm trying to take the new estimate from the output and create histogram. Can you please help?
Thank you.
You need to store the value for New Estimate during your loop. This way you can retrieve your results after the loop is finished. Normally when using a loop, you specify a variable in advance in which you can save the result for each iteration. E.g.:
numbers <- 1:3
result <- list(length = length(numbers)
for (i in seq_along(numbers){
result[[i]] <- numbers[[i]] + 1
}
In this example there is a vector of three numbers, you want to add one to each number and save the result. You can do this by creating a list of length 3 (adding length is better, but not necessary) and for each i
th iteration, you save the result in the i
th element of the list.
After finishing the loop you can retrieve the results from the result
variable. And you can retrieve the i
th result by using square brackets: result[[i]]
.