# NA's Produced When Number of Iterations Increase

I am trying to write a function that generates random paths for a Travelling Salesman Problem.

Here is the data:

``````final_data = data.frame(Longitude = rnorm(19, 40,1), Lattitude = rnorm(19, -65,1))

final_data\$id = 1:19

N <- nrow(final_data)

dists <- outer(seq_len(N), seq_len(N), function(a,b) {
geosphere::distHaversine(final_data[a,1:2], final_data[b,1:2]) })

D <- as.matrix(dists)

####

d = 19
fix_num <- 1
``````

Here is the function for 100 random paths:

``````results <- list()
resultss <- list()

for (i in 1:100)

{
start.time <- Sys.time()

iteration = i

relations_i = tibble(
from = c(fix_num, sample(setdiff(1:d, fix_num))),
)

relations_i = data.frame(relations_i)
relations_i\$iteration = i

m<-dists

my_sums_i = function(relations_i, m) {
r = as.matrix(relations_i)
if(mode(r) != "numeric") mode(r) = "numeric"
sum(m[r])}

m_i = my_sums_i(relations_i, m)

end.time <- Sys.time()
time.taken_i <- end.time - start.time

m_i\$time = time.taken_i

results[[i]] <- m_i

resultss[[i]] <- relations_i

}

results_1 <- data.frame(do.call(rbind.data.frame, results))
results_2 <- data.frame(do.call(rbind.data.frame, resultss))

####
``````

This seems to work fine - the problem happens when I Increase the number of paths (e.g. i =100 vs. i = 1000):

``````results <- list()
resultss <- list()

for (i in 1:1000)

{
start.time <- Sys.time()

iteration = i

relations_i = tibble(
from = c(fix_num, sample(setdiff(1:d, fix_num))),
)

relations_i = data.frame(relations_i)
relations_i\$iteration = i

m<-dists

my_sums_i = function(relations_i, m) {
r = as.matrix(relations_i)
if(mode(r) != "numeric") mode(r) = "numeric"
sum(m[r])}

m_i = my_sums_i(relations_i, m)

end.time <- Sys.time()
time.taken_i <- end.time - start.time

m_i\$time = time.taken_i

results[[i]] <- m_i

resultss[[i]] <- relations_i

}

results_1 <- data.frame(do.call(rbind.data.frame, results))
results_2 <- data.frame(do.call(rbind.data.frame, resultss))
``````
• For some reason, when there are more paths, NA's are produced in the results.
• Is there a way to fix this?

Thank you!

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.