[R] problem with using seq() or rep() inside a for loop
David Barron
dnbarron at gmail.com
Tue Jul 7 23:11:54 CEST 2015
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:
> 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