Skip to content

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

4 messages · Karl Schilling, David Barron, Boris Steipe +1 more

#
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
#
You need to put the expression on the right of the colon in your for
statement in parenthesis:

for (i in 1:(ncol(MD_dist) - 1)){
...
}
On 7 July 2015 at 19:00, Karl Schilling <karl.schilling at uni-bonn.de> wrote:
#
The fact that it works when you pass your i values "by hand" should alert you that perhaps your loop control does not do what you think it does.

Consider: 
Your version:
for(i in 1:6 - 1)

What you probably meant:
for(i in 1:(6 - 1)) print(i)

The error is created on the first iteration of your loop where you set i to 0. "by" can't be 0.




Cheers,
Boris
On Jul 7, 2015, at 2:00 PM, Karl Schilling <karl.schilling at uni-bonn.de> wrote:

            
#
for (i in 1:(ncol(MD_dist) - 1)){
   ...
   }

Even better, replace
   1:(n-1)
with
   seq_len(n-1)
The latter does what you want (and empty integer vector) when n is 1;
the former would give c(1,0).


Bill Dunlap
TIBCO Software
wdunlap tibco.com
On Tue, Jul 7, 2015 at 2:11 PM, David Barron <dnbarron at gmail.com> wrote: