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.

smci
  • 32,567
  • 20
  • 113
  • 146
gabriel
  • 399
  • 2
  • 7
  • 17

1 Answers1

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
mnel
  • 113,303
  • 27
  • 265
  • 254
  • 3
    Quick draw mcgraw you beat me by .000003 seconds +1 – Tyler Rinker Oct 09 '12 at 00:49
  • :) -- that's happened to me quite often – mnel Oct 09 '12 at 00:50
  • 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 you – gabriel Oct 09 '12 at 00:51
  • 3
    `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 `NULL` – mnel Oct 09 '12 at 00:56