收集来自副本的多值结果到一个数据框中。

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

Collecting multivalued results from replicate in a dataframe

问题

假设我有一个产生两列 x 和 y 的函数,我想复制它。

```r
myf <- function(){
  x = rnorm(1)
  y = x + runif(1)
  return(data.frame(x=x, y=y))
}

我如何获得所有结果的数据框,其中包含两列 x 和 y?

编辑:更新函数以使 x 和 y 相互依赖以提高清晰度。

results <- replicate(10, myf())


<details>
<summary>英文:</summary>

Suppose I have some function that produces two columns x and y, which I would like to replicate.

```r
myf &lt;- function(){
  x = rnorm(1)
  y = x + runif(1)
  return(data.frame(x=x, y=y))
}

How do I obtain a dataframe of all the results, with two columns x and y?

EDIT: updated function to dependent x & y for clarity

results <- replicate(10, myf())

答案1

得分: 2

你可以在replicate中使用 simplify = FALSE 标志,然后使用do.call(rbind, ...)组合结果。

set.seed(3244)
res <- do.call(rbind, replicate(10, myf(), simplify = FALSE))
res
英文:

You can do it with simplify = FALSE flag in replicate and rbind the results.

set.seed(3244)
res &lt;- do.call(rbind, replicate(10, myf(), simplify = FALSE))
res

#             x         y
#1  -0.87455516 0.4195560
#2  -1.45238736 0.5881533
#3   1.19270525 0.3095463
#4   2.07718022 0.8251412
#5   1.60242707 0.6113180
#6   1.06118593 0.3115188
#7   0.38004081 0.4001915
#8  -0.20526611 0.7026361
#9  -0.72092997 0.2526922
#10  0.09140117 0.2004964

huangapple
  • 本文由 发表于 2023年4月17日 21:45:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76035842.html
匿名

发表评论

匿名网友

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

确定