我想从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
到目前为止,我有:矩阵(样本(c(“MU”,“MG”,“PU”,“PG”),70*4,F),nrow=70,byrow=TRUE),这是不正确的,因为行可能有不止一个MU,MG,PU,PG的实例。我可以用for循环或更简单的方法来完成吗?
您也可以尝试以下方法:
lyst <- lapply( 1:70, function(x) {set.seed(x); sample(c("PU", "MU", "MG", "PG"), 4, replace=F)})
do.call("rbind", lyst)
作为输出的某些行的示例:
#[,1] [,2] [,3] [,4]
#[1,] "MU" "PG" "MG" "PU"
#[2,] "PU" "MG" "MU" "PG"
#[3,] "PU" "MG" "PG" "MU"
#[4,] "MG" "PU" "PG" "MU"
#[5,] "PU" "MG" "MU" "PG"
快速解决方案是循环:
mat <- matrix(NA_character_, nrow = 70, ncol = 4)
for (i in 1:70) {
mat[i, ] <- sample(c("MU","MG","PU","PG"), 4, replace = FALSE)
}
对于那些对循环过敏的人:
t(sapply(1:70, function(x) sample(c("MU","MG","PU","PG"), 4, replace = FALSE)))
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编程语言提供以下种类的循环来处理循环需求。可单击以下链接来查看其详细信息。 序号 循环语句 描述 1 repeat循环 多次执行一
编辑:重新措辞 我有一个账户列表:帐户 当我总结这份清单时,我得到了账户数量和账户总价值的概述 名称摘要 我添加了马克,因为他现在将是一个帐户所有者,但他目前没有任何帐户。 第一步是查看每个人应该拥有的账户的平均数。有25个账户,5个所有者,所以每个人都应该有5个账户。总价值为15600英镑,共有5名所有者,因此每个人的账户价值应该在3120英镑左右。这是一个估计值,所以我对它稍微偏离一点没意见。
我是最近一个R的转换者,正在努力寻找下面的R等价物:循环使用一个公共前缀加上一个数字(var1,var2,...,varn)命名的变量。 假设我有一个数据集,其中每行是一个商店,每列是该商店在第1个月、第2个月...第6个月的收入值。一些虚构的数据,例如: 你能提出一个适当的方法吗?
我认为无论如何我都必须在内循环上使用foreach,对吗?
我正在尝试从几个mutate(dplyr包)函数创建一个循环函数。下面的每一行代码都运行得很好,但是我正在寻找更优雅的代码(如果可能的话,在一行代码中),因为我需要再重复这五行代码10次(对于额外的10个数据帧)。 是我的Data.Frame,有5列10,000行。
我在尝试创建一个函数时遇到了麻烦。我想把数字转换成一周中指定的日子。例如:1='星期一',2='星期二',3='星期三',4='星期四',5='星期五',6='星期六',0='星期日' 下面是我编写函数的尝试,但我得到了一个错误,我还认为一定有一种方法可以循环它。我只是不知道怎么做。