简体   繁体   中英

R poisson simulation

I need to write a function which calculates the number of arrivals until time t in n trials. And the arguments should be the lambda (which I can assume to be between 0.1 and 1), the time (I can assume to be less than or equal to 1) and the number of counts to be sampled.

I've previously written a function which takes a vector of length n which has the first n -1 elements as inter-event times and the nth element as the time t , and it counts the number of events which occur before t .

inp <- readline(prompt="Input vector with each element seperated by a space")
inp <- strsplit(inp," ")
inp <- as.integer(as.vector(inp[[1]]))
t <- tail(inp, n=1)
c.e <- function(x) {
  inp = x
  stopped = NA
  for (i in seq_along(inp)) {
    runsum <- sum(inp[1:i])
    cat("The sum of the", i, "first elements is", runsum, "\n")

    if (runsum > tail(inp, 1)) {
      stopped = i - 1
      break()
    }
  }

  stopped
}
cat(c.e(inp), "events occur in", t, "time units")

(eg inputting 1 2 3 4 7 would output that 3 events occur in 6 time units)

I think I need to use and possibly edit this function in order to get it to do what I need it do, but I'm really not sure how to do this. Any help would be appreciated:)

You could edit this in to your old function if you want something like the printing and the nice inputs/outputs that you've got, but as for what you've actually asked for, it seems like all that you need is counts<-function(lambda, t, n) sum(rpois(n, lambda) < t) .

rpois generates the trial results, with parameters n (the number of trials) and lambda , we then compare them with t (time) and sum our results.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM