gpt4 book ai didi

r - for循环R中的样本

转载 作者:行者123 更新时间:2023-12-02 06:48:51 25 4
gpt4 key购买 nike

我想从 MU、MG、PU、PG 中采样 70 次以创建一个矩阵(ncol=4,nrow=70)例如

sample(c("MU","MG","PU","PG"), 4,F)
sample(c("MU","MG","PU","PG"), 4,F)
sample(c("MU","MG","PU","PG"), 4,F)
sample(c("MU","MG","PU","PG"), 4,F)
sample(c("MU","MG","PU","PG"), 4,F)
#etc

到目前为止,我有:matrix(sample(c("MU","MG","PU","PG"), 70*4,F), nrow = 70, byrow = TRUE) 这是不对的,因为行可能超过仅举 MU、MG、PU、PG 中的每一个实例。我可以使用 for 循环或更简单的方法来做到这一点吗?

最佳答案

replicate 函数可能正是您要寻找的。我只会重复 10 次,以免溢出屏幕。

> sample(c("MU","MG","PU","PG"), 4,F)
[1] "MG" "MU" "PU" "PG"
> replicate(10, sample(c("MU","MG","PU","PG"), 4,F))
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] "MG" "PG" "MU" "MU" "PU" "MG" "PU" "MG" "MG" "MU"
[2,] "PU" "MG" "PU" "PU" "MU" "MU" "MU" "PG" "MU" "PG"
[3,] "MU" "PU" "MG" "PG" "MG" "PG" "MG" "MU" "PG" "MG"
[4,] "PG" "MU" "PG" "MG" "PG" "PU" "PG" "PU" "PU" "PU"
> # Output is transposed from how we would want it so we'll just transpose it back
> t(replicate(10, sample(c("MU","MG","PU","PG"), 4,F)))
[,1] [,2] [,3] [,4]
[1,] "MG" "PU" "PG" "MU"
[2,] "PU" "MG" "MU" "PG"
[3,] "MG" "MU" "PU" "PG"
[4,] "PU" "PG" "MU" "MG"
[5,] "MG" "PU" "PG" "MU"
[6,] "PU" "PG" "MU" "MG"
[7,] "PG" "MG" "PU" "MU"
[8,] "MU" "PU" "MG" "PG"
[9,] "PG" "MU" "PU" "MG"
[10,] "MU" "MG" "PG" "PU"

关于r - for循环R中的样本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50256960/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com