Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the maximum value within a loop in R

Tags:

loops

r

I have an expression

 qbinom(0.05, n, .47) - 1 

and I want to create a loop which iterates this expression over n for n = (20,200). For each iteration of this loop, this function will produce a number. I want to take the maximum of the 180 numbers it will produce. So, something like.

 for (n in 20:200) {
   max(qbinom(0.05, n, .47)-1)

But I'm not sure how exactly to do this.

Thanks!

like image 573
roc11111111 Avatar asked Oct 04 '16 01:10

roc11111111


1 Answers

First, I will show you how to do this with a loop.

n <- 20:200
MAX = -Inf    ## initialize maximum
for (i in 1:length(n)) {
  x <- qbinom(0.05, n[i], 0.47) - 1
  if (x > MAX) MAX <- x
  }

MAX
# [1] 81

Note, I am not keeping a record of all 181 values generated. Each value is treated as a temporary value and will be overwritten in the next iteration. In the end, we only have a single value MAX.

If you want to at the same time retain all the records, we need first initialize a vector to hold them.

n <- 20:200
MAX = -Inf    ## initialize maximum
x <- numeric(length(n))    ## vector to hold record
for (i in 1:length(n)) {
  x[i] <- qbinom(0.05, n[i], 0.47) - 1
  if (x[i] > MAX) MAX <- x[i]
  }

## check the first few values of `x`
head(x)
# [1] 5 5 6 6 6 7

MAX
# [1] 81

Now I am showing the vectorization solution.

max(qbinom(0.05, 20:200, 0.47) - 1)
# [1] 81

R functions related to probability distributions are vectorized in the same fashion. For those related to binomial distributions, you can read ?rbinom for details.

Note, the vectorization is achieved with recycling rule. For example, by specifying:

qbinom(0.05, 1:4, 0.47)

R will first do recycling:

   p: 0.05    0.05    0.05    0.05
mean:    1       2       3       4
  sd: 0.47    0.47    0.47    0.47

then evaluate

qbinom(p[i], mean[i], sd[i])

via a C-level loop.


Follow-up

How would I be able to know which of the 20:200 corresponds to the maximum using the vectorization solution?

We can use

x <- qbinom(0.05, 20:200, 0.47) - 1
i <- which.max(x)
# [1] 179

Note, i is the position in vector 20:200. To get the n you want, you need:

(20:200)[i]
# 198

The maximum is

x[i]
# [1] 81
like image 83
Zheyuan Li Avatar answered Sep 28 '22 10:09

Zheyuan Li