如何在R中的循环内找到最大值 [英] How to find the maximum value within a loop in R

查看:167
本文介绍了如何在R中的循环内找到最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表达

 qbinom(0.05, n, .47) - 1 

,我想创建一个循环,使该表达式遍历n =(20,200).对于此循环的每次迭代,此函数都会产生一个数字.我要最多使用它会产生的180个数字.所以,像这样.

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.

谢谢!

推荐答案

首先,我将向您展示如何循环执行此操作.

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

注意,我没有保存所有181个值的记录.每个值都被视为一个临时值,并将在下一次迭代中覆盖.最后,我们只有一个值 MAX .

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


现在,我正在展示矢量化解决方案.

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

与概率分布相关的

R个函数以相同的方式矢量化.对于与二项式分布有关的那些,您可以阅读?rbinom 以获得详细信息.

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将首先进行回收:

   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 中的哪个对应于最大值?

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

我们可以使用

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

请注意, i 是向量 20:200 中的位置.要获取所需的 n ,您需要:

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

(20:200)[i]
# 198

最大为

x[i]
# [1] 81

这篇关于如何在R中的循环内找到最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆