Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/webpack/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在没有for循环的情况下重复操作序列_R - Fatal编程技术网

在没有for循环的情况下重复操作序列

在没有for循环的情况下重复操作序列,r,R,我在R中进行了一个模拟,涉及执行几行代码。 我想把这个过程复制1000次 在没有for循环的情况下,有没有办法做到这一点 我知道有replicate(),但它一次只能复制一个进程 下面是一个例子: for (r in 1:reps){ first<-sapply(1:100, function(x) sample(c(1,2),100,prob=c(0.45,0.55),replace=T)) second<-sapply(2:100, function(i) length(wh

我在R中进行了一个模拟,涉及执行几行代码。 我想把这个过程复制1000次

在没有for循环的情况下,有没有办法做到这一点

我知道有replicate(),但它一次只能复制一个进程

下面是一个例子:

for (r in 1:reps){

first<-sapply(1:100, function(x) sample(c(1,2),100,prob=c(0.45,0.55),replace=T))

second<-sapply(2:100, function(i) length(which(apply(sapply(1:100, function(x) sample(easy[x,],i)),2,max)==2)) )

third[r,]<-second
}   
for(r/1:重复){

首先正如我在评论中提到的,类似这样的东西可以避免循环

foo = function (dummy) {
first<-sapply(1:100, function(x) sample(c(1,2),100,prob=c(0.45,0.55),replace=T))

second<-sapply(2:100, function(i) length(which(apply(sapply(1:100, function(x) sample(easy[x,],i)),2,max)==2)) )

third[r,]<-second
}

sapply(1:reps, foo)
foo=函数(虚拟){

首先命令
replicate
对您很有用(它实际上只是
sapply
的包装,但使您的代码更具可读性)。我还使您的循环内部更具可读性:

set.seed(123)
for (r in 1:reps){  
  #  first <- matrix(sample(c(1,2),100*100,prob=c(0.45,0.55),replace=T), nrow=100)
  second <- sapply(2:100, function(i) length(which(apply(sapply(1:100, function(x) sample(easy[x,],i)),2,max)==2)) )
  third[r,]<-second
}   
set.seed(123)
third.2 <- t(replicate(reps, sapply(2:100, function(i) 
  sum(apply(easy[1:100, ], 1, function(x) max(sample(x, i))==2)))))
all.equal(third, third.2)

从理论上讲,你可以把它放到一个函数中,然后再次使用
sapply
,但你想实现什么?定义为什么是
easy
?这很好,但第三行行不通,因为它使用reps作为索引。如果不定义
reps
easy
,你怎么能运行它呢?我不能,但我想maki一个可复制的例子应该是问题的一部分,而不是答案(当然,如果问题有一个可复制的例子,答案应该跟进)。仅供参考,我使用了
reps表示同意。你的
set.seed()
calls让我厌烦了。:)我想,如果OP想将我的输出与他的原始输出进行比较,那么只有在适当的种子下才有意义。但我同意,这有点让人困惑。
set.seed(123)
first <- sapply(1:100, function(x) sample(c(1,2),100,prob=c(0.45,0.55),replace=T))
set.seed(123)
first.2 <- matrix(sample(c(1,2), 100*100, prob=c(0.45,0.55), replace=T), nrow=100)
all.equal(first, first.2)