Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two interdepending for loops in R, strange results

Tags:

loops

r

I try to calculate something in R for different paramter values a and b, where my parameter b always should be smaller or equal to a. To do this, I make two loops where I vary a (from 0 to 4) and then b from 0 to a, but R gets me strange values of b.

v=c()
L<-0
for (a in seq(0, 4, length.out=41)){
  for (b in seq(0, a, length.out=(10*a+1))){
    L<-L+1
    v[L]<-b
  }
}
v

It seems to me that b should always run from 0 to a in 0.1 steps. But it does not always, sometimes the steps are smaller, as can be seen in positions 23-28 of vector v (for example). Does anybody have an idea why this is the case. I can't find the mistake! Thanks!

like image 450
user2599492 Avatar asked Dec 26 '22 00:12

user2599492


2 Answers

The documentation for seq notes that the value of length.out will be rounded up. Since a is numeric and thus is associated with some error, it's possible to get a length of one more than you expect, which gives you the weird output.

for (a in seq(0, 4, length.out=41)[1:7]){
  print(paste(as.integer(10*a+1), ceiling(10*a+1)))
}
# [1] "1 1"
# [1] "2 2"
# [1] "3 3"
# [1] "4 4"
# [1] "5 5"
# [1] "6 6"
# [1] "7 8"

Notice the last line: you get 8 instead of 7.

To solve this, try converting the length to an integer yourself by rounding:

for (b in seq(0, a, length.out=round(10*a+1))){
like image 122
Peyton Avatar answered Jan 05 '23 06:01

Peyton


What's wrong with the old fashioned way to do it?

v=c()
L<-0
for (a in 0:40){
    for (b in 0:a){
    L<-L+1
    v[L]<-b/10
  }
}
v
like image 36
Peter Dutton Avatar answered Jan 05 '23 07:01

Peter Dutton