algui91 algui91 -4 years ago 93
R Question

Reshape each row of a data.frame to be a matrix in R

I am working with the hand-written zip codes dataset. I have loaded the dataset like this:

digits <- read.table("./zip.train",
quote = "",
comment.char = "",
stringsAsFactors = F)


Then I get only the ones:

ones <- digits[digits$V1 == 1, -1]


Right now, in
ones
I have 442 rows, with 256 column. I need to transform each row in
ones
to a 16x16
matrix
. I think what I am looking for is a list of 16x16 matrix like the ones in this question:

How to create a list of matrix in R

But I tried with my data and did not work.

At first I tried
ones <- apply(ones, 1, matrix, nrow = 16, ncol = 16)
but is not working as I thought it was. I also tried
lapply
with no luck.

Answer Source

though there are probably simple ways, you can try with lapply:

ones_matrix <- lapply(1:nrow(ones), function(i){matrix(ones[i, ], nrow=16)})
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download