# Basic graphical R code draws an ellipse instead of a circle

I wrote some very basic R code.

This has at least two problems.

1. It uses a very basic imperative-programming style instead of good R style.

2. 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<-100
magicmargin=.01
width<-(2*edge)+1

x<-c(-edge:edge)
y<-c(-edge:edge)

squarelist<-c(1:((width^2)))

dim(squarelist)<-c(width, width)

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

}
}
}

gg<-matrix(squarelist,nrow=width,ncol=width)

image(gg)

• fix for Problem 2: image(gg, asp=1) – rcs Nov 21 '13 at 21:19

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

edge <- 100
magicmargin <- .01
width <- (2*edge) + 1

x <- -edge:edge
y <- -edge:edge

mat <- outer(x, y, function(x,y) sqrt(x^2 + y^2))
ind <- mat > ((magicradius-magicmargin)*edge) & The aspect ratio in image() can be set with the asp argument (see the Details section in ?plot.window)