Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a matrix from vector returned by rep() function?

Tags:

r

vector

matrix

rep

x=1:20

[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

rep(x,2)

[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

View(rep(x,2))

Having a problem with generating a 20 by 2 vector using the rep() function in R.

Instead of creating two columns, each running from 1 to 20, when I view the data in the R workspace, it is displayed as 40X1 vector i.e. 1-20 1-20.

How do you use the rep() function to create a repeated column vector of 20X2? Thank you.

like image 715
gabriel Avatar asked Oct 09 '12 00:10

gabriel


People also ask

How can I create a matrix in R?

To create a matrix in R you need to use the function called matrix(). The arguments to this matrix() are the set of elements in the vector. You have to pass how many numbers of rows and how many numbers of columns you want to have in your matrix. Note: By default, matrices are in column-wise order.

Which function is used to build a matrix from two vectors in R programming?

rbind() function in R programming is used to combine vectors, data frames or matrices by rows and number of columns of data sets should be equal otherwise, output will be insignificant.

How do you create a matrix?

To create an array with four elements in a single row, separate the elements with either a comma ( , ) or a space. This type of array is a row vector. To create a matrix that has multiple rows, separate the rows with semicolons. Another way to create a matrix is to use a function, such as ones , zeros , or rand .


1 Answers

rep will return an atomic vector. If you want a matrix, use matrix on the results, with the appropriate dimensions.

eg.

x <- 1:20
matrix(rep(x,2), ncol = 2)
      [,1] [,2]
 [1,]    1    1
 [2,]    2    2
 [3,]    3    3
 [4,]    4    4
 [5,]    5    5
 [6,]    6    6
 [7,]    7    7
 [8,]    8    8
 [9,]    9    9
[10,]   10   10
[11,]   11   11
[12,]   12   12
[13,]   13   13
[14,]   14   14
[15,]   15   15
[16,]   16   16
[17,]   17   17
[18,]   18   18
[19,]   19   19
[20,]   20   20
like image 100
mnel Avatar answered Oct 06 '22 08:10

mnel