【发布时间】: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
大家好,我想将代码重复 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
最简单的方法是使用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
【讨论】: