【问题标题】:R for loop: perform iteration for every loopR for循环:为每个循环执行迭代
【发布时间】:2021-04-13 06:19:58
【问题描述】:

我正在尝试在 R 中运行模拟,但我无法编写正确的 for 循环。

我尝试执行的迭代是

i=1
distance<-NULL
for(i in 1:48)
{  
sample<-coordinates[sample(.N, i)]
meand = (dist(cbind(sample$x,sample$y)))
ppp<-sample
table<-as.matrix(dist(ppp))
table[table == 0] <- 1000
maxmin<-apply(table, 1, FUN=min)
distance.1<-mean(maxmin)
distance<-rbind(distance,distance.1)
}

结果给出了一个 48 行的结果数据框,其中 i = 1:48

我想做的是为 for 循环中的每个 i 运行大约 1000 次迭代。然后我想存储 1000 个结果的平均值,并为每个 i 存储它们。

我认为 replicate() 函数可能是解决方案,但我无法使用它们。

所以预期的输出有点


i=1    a   (average of 1000 iteration)
i=2    b   (average of 1000 iteration)
i=3    c   (average of 1000 iteration)
.
.
. 
i=48   d   (average of 1000 iteration)

我应该如何重写我的代码以执行快速迭代?我真诚地感谢一些帮助。

编辑

dput(coordinates)
structure(list(x = c(0.24, 0.72, 1.2, 3.675, 4.155, 4.635, 5.115, 
5.595, 6.075, 8.55, 9.03, 9.51, 9.99, 10.47, 10.95, 13.425, 13.905, 
14.385, 14.865, 15.345, 15.825, 18.3, 18.78, 19.26, 19.26, 18.78, 
18.3, 15.825, 15.345, 14.865, 14.385, 13.905, 13.425, 10.95, 
10.47, 9.99, 9.51, 9.03, 8.55, 6.075, 5.595, 5.115, 4.635, 4.155, 
3.675, 1.2, 0.72, 0.24), y = c(0.24, 0.24, 0.24, 0.24, 0.24, 
0.24, 0.24, 0.24, 0.24, 0.24, 0.24, 0.24, 0.24, 0.24, 0.24, 0.24, 
0.24, 0.24, 0.24, 0.24, 0.24, 0.24, 0.24, 0.24, 2.88, 2.88, 2.88, 
2.88, 2.88, 2.88, 2.88, 2.88, 2.88, 2.88, 2.88, 2.88, 2.88, 2.88, 
2.88, 2.88, 2.88, 2.88, 2.88, 2.88, 2.88, 2.88, 2.88, 2.88)), row.names = c(NA, 
-48L), class = c("data.table", "data.frame"), .internal.selfref = <pointer: 0x0000027c2a7f1ef0>)

【问题讨论】:

  • 提供可重现的数据样本 (?coordinates?)。 .N 是什么?告诉我们你想要完成什么。看起来您正在计算用 1 - 48 列坐标计算的距离,并试图找到最小距离的平均值?
  • @dcarlson 是的,我正在尝试计算最小距离的平均值。点数在 for 循环中的“i”中。目前坐标是固定的,但稍后我会在坐标中添加一些随机分布的点。我将使用可重现的样本编辑问题。

标签: r loops for-loop iteration replicate


【解决方案1】:

如果我正确理解了您的问题,apply 函数可能可以很好地解决您的问题。下面,我只是嵌套一个sapply 来在每个i 中进行1000 次额外的复制。

sapply(1:48, function(i){  
  mean(sapply(1:1000, function(x){
    sample<-coordinates[sample(.N, i)]
    meand = (dist(cbind(sample$x,sample$y)))
    ppp<-sample
    table<-as.matrix(dist(ppp))
    table[table == 0] <- 1000
    maxmin<-apply(table, 1, FUN=min)
    mean(maxmin)
  }))
})

我会更容易与您的数据样本。祝你好运!

【讨论】:

  • 我认为这只是我的预期结果。太感谢了!! sapply 似乎是一种解决方案。再次感谢您。
  • 我很高兴并祝您分析顺利! :)