By Vahid Mirjalili


2013-07-19 18:13:50 8 Comments

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?

2 comments

@jared 2018-06-23 03:16:59

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

@flodel 2013-07-19 18:17:02

You can do

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

or

d <- matrix(d, nrow = 10, byrow = TRUE)

Related Questions

Sponsored Content

10 Answered Questions

[SOLVED] Convert data.frame column to a vector?

6 Answered Questions

[SOLVED] Reshape three column data frame to matrix ("long" to "wide" format)

19 Answered Questions

[SOLVED] How to sort a dataframe by multiple column(s)

20 Answered Questions

[SOLVED] Split a vector into chunks in R

  • 2010-07-23 13:01:03
  • Sebastian
  • 141230 View
  • 205 Score
  • 20 Answer
  • Tags:   r vector

16 Answered Questions

[SOLVED] Changing column names of a data frame

  • 2011-05-21 11:31:23
  • Son
  • 1231629 View
  • 362 Score
  • 16 Answer
  • Tags:   r dataframe rename

9 Answered Questions

[SOLVED] Grouping functions (tapply, by, aggregate) and the *apply family

1 Answered Questions

4 Answered Questions

[SOLVED] How to reshape vector into sqare matrix?

2 Answered Questions

[SOLVED] Reshape column vector

1 Answered Questions

[SOLVED] Replace Matrix Values with Vectors, One Column at a Time

Sponsored Content