I have a vector I would like to repeat n times using the vector as columns in the new matrix
ie I have a vector
vec <- c(266, 130, 86, 69, 56, 39, 30, 44, 33, 43)
vec
[1] 266 130 86 69 56 39 30 44 33 43
I would like to produce n times
vec1 vec1
266 266
130 130
86 86
69 69
56 56
39 39
30 30
44 44
33 33
43 43 .....
I am not entirely familiar with do.call but would you use that function to achieve this ?
R recycles vectors when you create a matrix, so you can use:
matrix( vec , length(vec) , n )
where n
is the number of columns/repetitions.
Another obvious alternative here is to use replicate
(though matrix
should be more efficient):
> vec <- scan()
1: 266 130 86 69 56 39 30 44 33 43
11:
Read 10 items
> replicate(5, vec)
[,1] [,2] [,3] [,4] [,5]
[1,] 266 266 266 266 266
[2,] 130 130 130 130 130
[3,] 86 86 86 86 86
[4,] 69 69 69 69 69
[5,] 56 56 56 56 56
[6,] 39 39 39 39 39
[7,] 30 30 30 30 30
[8,] 44 44 44 44 44
[9,] 33 33 33 33 33
[10,] 43 43 43 43 43
Or, you could take a more cryptic (but possibly faster) approach like:
`dim<-`(rep(vec, 5), c(length(vec), 5))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.