【问题标题】:repeat the the following code n times in R在R中重复以下代码n次
【发布时间】:2022-01-13 17:43:24
【问题描述】:

大家好,我想将代码重复 n 次,并将 x 的结果保存到 R 程序中的向量中。你能帮忙用 R 写这个吗?

x<-c()
i<-1
y<-c()
repeat {
    
    x[i]<-runif(1)
    i=i+1
    if(sum(x)>1) {
      break
    }
  }

x

【问题讨论】:

    标签: r statistics


    【解决方案1】:

    最简单的方法是使用replicate。首先将您的代码转换为函数:

    myfunction <- function() {
      x <- c()
      i <- 1
      repeat {
        x[i] <- runif(1)
        i <- i + 1
        if(sum(x) > 1) {
             return(x)
          break
        }
      }
    }
    

    请注意,我们必须从函数中显式返回 x。现在使用 replicate 多次运行该函数:

    set.seed(42)   # Use for repeatability of the example
    results <- replicate(10, myfunction())
    

    现在results 是一个列表,每次运行都是一个单独的元素:

    results[[1]]
    # [1] 0.9148060 0.9370754
    sapply(results, length)   # How many elements in each run
    # [1] 2 2 2 3 2 2 3 2 2 2
    sapply(results, sum)      # What was the sum of each run
    #  [1] 1.851881 1.116587 1.160841 1.528247 1.162807 1.653784 1.657736 1.095714 1.035330 1.042742
    

    【讨论】:

    • 谢谢你,这是一个很好的答案
    猜你喜欢
    • 1970-01-01
    • 2017-10-02
    • 1970-01-01
    • 2018-02-17
    • 2016-05-30
    • 2015-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多