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

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

Collecting multivalued results from replicate in a dataframe

问题

  1. 假设我有一个产生两列 x y 的函数,我想复制它。
  2. ```r
  3. myf <- function(){
  4. x = rnorm(1)
  5. y = x + runif(1)
  6. return(data.frame(x=x, y=y))
  7. }

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

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

results <- replicate(10, myf())

  1. <details>
  2. <summary>英文:</summary>
  3. Suppose I have some function that produces two columns x and y, which I would like to replicate.
  4. ```r
  5. myf &lt;- function(){
  6. x = rnorm(1)
  7. y = x + runif(1)
  8. return(data.frame(x=x, y=y))
  9. }

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, ...)组合结果。

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

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

  1. set.seed(3244)
  2. res &lt;- do.call(rbind, replicate(10, myf(), simplify = FALSE))
  3. res
  4. # x y
  5. #1 -0.87455516 0.4195560
  6. #2 -1.45238736 0.5881533
  7. #3 1.19270525 0.3095463
  8. #4 2.07718022 0.8251412
  9. #5 1.60242707 0.6113180
  10. #6 1.06118593 0.3115188
  11. #7 0.38004081 0.4001915
  12. #8 -0.20526611 0.7026361
  13. #9 -0.72092997 0.2526922
  14. #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:

确定