Basic graphical R code draws an ellipse instead of a circle I wrote some very basic R code.

This has at least two problems.


It uses a very basic imperative-programming style instead of good R style.
It draws the result as an ellipse, not a circle.  This effect is barely visible on RGui on Windows, but extremely visible in RStudio on Linux. [Edit: rcs has mentioned that the asp parameter of the image command can fix this. Thanks, rcs.]


There are some debatable issues.  For example, there is no good reason why I draw the radius at the distance that I do, so I consider this to be a "magic" number, and I try to avoid "magic numbers" in code because they cause maintenance problems.  The number is in there because I don't think it's worthwhile specifying a user input or a function argument to control it.

edge&lt;-100
magicradius=.81
magicmargin=.01
width&lt;-(2*edge)+1

x&lt;-c(-edge:edge)
y&lt;-c(-edge:edge)

squarelist&lt;-c(1:((width^2)))

dim(squarelist)&lt;-c(width, width)

counter&lt;-0
for (i in 1:length(x)){
  for (j in 1:length(y)){
    counter&lt;-counter+1
    if( (((magicradius-magicmargin)*(edge))&lt;sqrt( x[i]^2 + y[j]^2  ) )
        &amp;(((magicradius+magicmargin)*(edge))&gt;sqrt( x[i]^2 + y[j]^2 ) ) ){
      squarelist[counter]&lt;-sqrt( x[i]^2 + y[j]^2)
    } else {
      squarelist[counter]&lt;-0

    }      
  }
}

gg&lt;-matrix(squarelist,nrow=width,ncol=width)

image(gg)
A vectorized solution using outer (Outer Product of Arrays):

edge &lt;- 100
magicradius &lt;- .81
magicmargin &lt;- .01
width &lt;- (2*edge) + 1

x &lt;- -edge:edge
y &lt;- -edge:edge

mat &lt;- outer(x, y, function(x,y) sqrt(x^2 + y^2))
ind &lt;- mat &gt; ((magicradius-magicmargin)*edge) &amp;
       mat &lt; ((magicradius+magicmargin)*edge)
image(ind, asp=1)




The aspect ratio in image() can be set with the asp argument (see the Details section in ?plot.window)