[R] problem with using seq() or rep() inside a for loop

Karl Schilling karl.schilling at uni-bonn.de
Tue Jul 7 20:00:55 CEST 2015


Dear All:

I want to use seq() inside a for-loop and use the looping counter i as 
the "by" argument in seq(). Here is some exemplary data and code:

# set up some data
distances <- c(0, NA, NA, NA, NA, NA,
                5, 0, NA, NA, NA, NA,
                5, 2, 0, NA, NA, NA,
                18, 5, 5, 0, NA, NA,
                25, 10, 8, 1, 0, NA,
                41, 20, 18, 5, 2, 0)

MD_dist <- matrix(distances, ncol = 6)

MEAN <- numeric(nrow(MD_dist) - 1) # just to set up a vector

# loop to add (subsets of) off-diagonal diagonal values
for(i in 1: ncol(MD_dist) - 1){
diagonal <- as.vector(MD_dist[row(MD_dist) == (col(MD_dist) - i)])
# the following line extracts every i-th element from "diagonal"
diagonal.2 <- diagonal[seq(1, to = length(diagonal), by = i)]
MEAN[i] <- mean(diagonal.2)
}

However, I keep getting the following error message:

Error in seq.default(1, to = length(diagonal), by = i) :
   invalid (to - from)/by in seq(.)

May I add that if I run the loop "by hand" - i.e. by just setting i = 1, 
2... etc and then running the core without the for {...} , everything 
works fine.

Further, when I use rep(..) instead of seq(...) to extract the desired 
values from "diagonal", I have the very same problem - it works outside 
a for loop, but fails inside.

I am using R 3.2.1. (x64) under Win 7 Professional on a 64 bit machine.

Any suggestion would be appreciated.

Thank you so much.

Karl

-- 
Karl Schilling



More information about the R-help mailing list