Alejandro Alcalde
Alejandro Alcalde

Reputation: 6220

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.

Upvotes: 1

Views: 404

Answers (2)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193687

An alternative is to just change the dims of your matrix.

Consider the following matrix "M":

M <- matrix(1:12, ncol = 4)
M
#      [,1] [,2] [,3] [,4]
# [1,]    1    4    7   10
# [2,]    2    5    8   11
# [3,]    3    6    9   12

We are looking to create a three dimensional array from this, so you can specify the dimensions as "row", "column", "third-dimension". However, since the matrix is constructed by column, you first need to transpose it before changing the dimensions.

`dim<-`(t(M), c(2, 2, nrow(M)))
# , , 1
# 
#      [,1] [,2]
# [1,]    1    7
# [2,]    4   10
# 
# , , 2
# 
#      [,1] [,2]
# [1,]    2    8
# [2,]    5   11
# 
# , , 3
# 
#      [,1] [,2]
# [1,]    3    9
# [2,]    6   12

Upvotes: 4

Cath
Cath

Reputation: 24074

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

ones_matrix <- lapply(1:nrow(ones), function(i){matrix(ones[i, ], nrow=16)})

Upvotes: 2

Related Questions