Reputation: 91
I try to reproduce a figure from a book(figure 1.2 from Elements of Statistical Learning). The image from the book is based on a very big matrix(zip code, Test data: http://statweb.stanford.edu/~tibs/ElemStatLearn/). I try to create this image with the following R code:
lettre <- read.table("C:/Users/.../Desktop/zip.test.gz")
lettres = as.matrix(lettre)
image(lettres)
I know that I have to use the function image and the function gray(for black and white), but with this code, I know that my picture is to correct. It is a big red image.
I am very not familiar with these functions. I tried to read and understand the description, but it did not help me. Any hint will be really appreciate.
Upvotes: 1
Views: 4265
Reputation: 32416
image
s are quite confusing in R. There are a couple of formatting issues here. First, the data is stored in rows of 256 values for each test image. So, this should be rearranged into a matrix of proper dimensions (16x16). Also, be careful how you read the data to a matrix, whether it should be by row or column (as in R). Then, once this is done, the matrix needs to be reversed by column and transposed.
So, to look at the first test case (a 'nine'),
m <- as.matrix(lettre)
first <- matrix(m[1,2:ncol(m)], 16, 16, byrow=T)
image(t(apply(first, 2, rev)), col=grey(seq(0,1,length=256)))
To put many of the images together, you could split up the test matrix into a list of properly aligned matrices, then combine however many you want.
## Split the matrix into a list of all the properly aligned images
images <- lapply(split(m, row(m)), function(x) t(apply(matrix(x[-1], 16, 16, byrow=T), 2, rev)))
## Plot 36 of them
img <- do.call(rbind, lapply(split(images[1:36], 1:6), function(x) do.call(cbind, x)))
image(img, col=grey(seq(0,1,length=100)))
Upvotes: 2