How to find the maximum value in a loop in R

I have an expression

 qbinom(0.05, n, .47) - 1 

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

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

But I'm not sure how to do this.

Thank!

+4
source share
1 answer

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 do not keep a record of all 181 generated values. Each value is considered a temporary value and will be overwritten at the next iteration. In the end, we have only one meaning MAX.

, .

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

.

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

R-, , . , , ?rbinom .

, . , :

qbinom(0.05, 1:4, 0.47)

R :

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

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

C.


, 20: 200 , ?

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

. i - 20:200. n, , :

(20:200)[i]
# 198

x[i]
# [1] 81
+6
source

Source: https://habr.com/ru/post/1656649/


All Articles