Fractals with R, Part 2: the Sierpiński Carpet

by Allan Roberts

This post is a variation on the previous post, Fractals with R. Here it is shown how a different fractal pattern can be produced by just a slight variation in the R script; the result is an iteration of a fractal called the Sierpiński Carpet. The method used here is basically the same as that described in Weisstein (2012). Below is the R script that produces the image.

Figure 1. An iteration in the construction of the Sierpiński Carpet, which I produced using R.

This fractal is an example of a pattern with both large and small patches. There are also distributions in ecology which are patchy across scales; see, for example Levin (1992). You might find the Sierpiński Carpet somewhat reminiscent of a fragmented eelgrass bed, or a distribution of mussels and barnacles in the intertidal.

From the point of view of handling data structures, this Sierpiński Carpet plot is an exercise in using the “rbind” and “cbind” functions in R, which allow you to aggregate matrices and data frames. I’ve found these functions useful for working with oceanographic data, such as that plotted in my posts on how to plot NEPTUNE Canada data and VENUS network data. For more, see Fractals with R, Part 3.

R Script

IterateCarpet <- function(A){
B <- cbind(A,A,A);
C <- cbind(A,0*A,A);
D <- rbind(B,C,B);

S <- matrix(1,1,1);
for (i in 1:5) S <- IterateCarpet(S);

image(S,col=c(0, 12), axes=FALSE);


Levin, Simon A., 1992. The Problem of Pattern and Scale in Ecology:  The Robert H. MacArthur Award Lecture. Ecology, 73 (6), 1992, pp. 1943-1967.

 R Development Core Team, 2011. R: A language and environment for statistical computing. R Foundation for Statistical Computing, Vienna, Austria.

Weisstein, Eric W. “Sierpiński Carpet.” From MathWorld– A Wolfram Wed Resource Accessed Oct. 22, 2012:

3 thoughts on “Fractals with R, Part 2: the Sierpiński Carpet

  1. Pingback: Fractals with R | The Madreporite

  2. Pingback: Fractals with R, Part 3: The Hilbert Curve | The Madreporite

  3. Pingback: Fractals with R, Part 5: Sierpinski Carpet with ggplot2 | The Madreporite

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s