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

1

13

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.

Shealy answered 9/10, 2012 at 0:46 Comment(0)
D
23

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
Deborahdeborath answered 9/10, 2012 at 0:48 Comment(4)
Quick draw mcgraw you beat me by .000003 seconds +1Exterminatory
:) -- that's happened to me quite oftenDeborahdeborath
Hey mnel, thank you. I noticed when I create a vector in R, such as x=1:20, R can give it length (length(x)=20) but when I ask it for the dimensions of the vector it gives me a NULL (dim(x)=NULL). How is R recognizing these vectors when they are created? Thank youShealy
dim will return the dim attribute of an object (such as a matrix or array or data.frame), vectors do not have a dim attribute. An atomic vector has length, but no dim attribute, thus it returns NULLDeborahdeborath

© 2022 - 2024 — McMap. All rights reserved.