生成随机数组值,直到达到总值在R中。

huangapple go评论52阅读模式
英文:

Generate random values in array until a total value is reached in R

问题

N <- array(0, years) # 创建数组
max.size <- 3 # 数组中的最大值
N = c(1,3,0,2,0,1,2,1,0,0,0,0,0,0,0,0,0,0,0,0) # 结果数组
random.sample <- function(x) { repeat {

做某事

i <- sample(0:max.size, 1)
x <- i

如果条件满足则退出

if (sum(x) == tot) break } return(x) }
random.sample(N)

英文:

I want to create an array, then assign a value to each place until the sum of values in the array equals a given total. Once the maximum value is reached the rest of the array can be 0. So to start:

years &lt;- 20 # total length of array

N &lt;- array(0, years) # make array

tot &lt;- 10 # Total I want to stop at

max.size &lt;- 3 # maximum value to put in the array

So the result may look something like: N = c(1,3,0,2,0,1,2,1,0,0,0,0,0,0,0,0,0,0,0,0)

I think a while statement would work, similar to this question, but not sure how to get there. Also, I think this question has the pieces I need, but am struggling to put them into my context.

random.sample &lt;- function(x) {  repeat {
# do something
i &lt;- sample(0:max.size, 1)
x &lt;- i
# exit if the condition is met
if (sum(x) == tot) break } return(x) }        
random.sample(N)

Thanks for your time.

答案1

得分: 2

以下是您要翻译的内容:

A simple function using cumsum and ifelse would do the job without requiring costly loops. The last clause just ensures the numbers add to tot

f <- function(len, tot, max.size) {
  x <- sample(0:max.size, len, replace = TRUE)
  res <- ifelse(cumsum(x) > tot, 0, x)

  if(sum(res) < tot) {
    res[(cumsum(res) == sum(res)) & res == 0][1] <- tot - sum(res)
  }
  res
}

Testing

f(len = 20, tot = 10, max.size = 3)
#> [1] 3 3 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
英文:

A simple function using cumsum and ifelse would do the job without requiring costly loops. The last clause just ensures the the numbers add to tot

f &lt;- function(len, tot, max.size) {
  x &lt;- sample(0:max.size, len, replace = TRUE)
  res &lt;- ifelse(cumsum(x) &gt; tot, 0, x)

  if(sum(res) &lt; tot) {
    res[(cumsum(res) == sum(res)) &amp; res == 0][1] &lt;- tot - sum(res)
  }
  res
}

Testing

f(len = 20, tot = 10, max.size = 3)
#&gt; [1] 3 3 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

huangapple
  • 本文由 发表于 2023年2月10日 03:28:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/75403521.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定