Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
286 views
in Technique[技术] by (71.8m points)

R for loop: perform iteration for every loop

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>)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If I understood correctly your question, apply functions might work just fine to solve your problem. Below, I'm just a nesting a sapply to do the 1000 additional replicates within each i.

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)
  }))
})

I'd be easier with a sample of your data. Good luck!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...