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

Boris Steipe boris.steipe at utoronto.ca
Tue Jul 7 23:12:55 CEST 2015


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:

> 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
> 
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list