I am trying to run a simulation in R, but I am having trouble writing the proper for loop.
The iteration I am trying to perform is
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)
}
The result give a 48 row dataframe of results ,where i = 1:48
What I would like to do is run about 1000 iteration for each i in the for loop. Then I would like to store the average of the 1000 results, and store them for each i.
I am thinking that replicate() function might be the solution, but I am having trouble using them.
So the expected output is somewhat
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)
How should I rewrite my code to perform a fast iteration? I would sincerely appreciate some help.
EDIT
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>)