22Jan/100
R Recipe: Repeating Columns in a Matrix using R
Someone recently asked me how to repeat a column in a matrix or dataframe using R. It's actually amazingly simple:
> x <- c(1,2,3,4,5)
> mx <- as.matrix(x) #this part is crucial
> y <- mx[,rep(1,10)] #this will repeat column 1 ten times
> y
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 1 1 1 1 1 1 1 1 1 1
[2,] 2 2 2 2 2 2 2 2 2 2
[3,] 3 3 3 3 3 3 3 3 3 3
[4,] 4 4 4 4 4 4 4 4 4 4
[5,] 5 5 5 5 5 5 5 5 5 5 |