英文:
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 <- 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 <- 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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论