Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R reshape a vector into multiple columns

Let's say I have a vector in R as follows:

d<-seq(1,100)

I want to reshape this vector into a 10x10 matrix, so that I will have this data instead:

[,1]  [,2]  [,3]  ..  [,10]   
  1      2    3   ..   10
  11    12   13   ..   20
  21    22   23   ..   30
  ..
  91    92   93    ..  100

I tried to use reshape function, but it didn't work. Can someone help please?

like image 892
Vahid Mirjalili Avatar asked Jul 19 '13 18:07

Vahid Mirjalili


2 Answers

You can do

dim(d) <- c(10, 10)
d <- t(d)

or

d <- matrix(d, nrow = 10, byrow = TRUE)
like image 165
flodel Avatar answered Nov 10 '22 17:11

flodel


If you want to convert a predifined list to a matrix (e.g. a 5*4 matrix), do

yourMatrix <- matrix(unlist(yourList), nrow = 5, ncol = 4)

It is worth noting that the matrix is created by columns, which means your data will be filled into the matrix by columns. So, if you want to the matrix created by rows, simply using t(), such as

yourMatrix <- matrix(unlist(yourList), nrow = 4, ncol = 5)  # exchanges the cols and rows
yourMatrix <- t(yourMatrix)  # matrix transpose
like image 2
jared Avatar answered Nov 10 '22 19:11

jared