Q:

how to repeat column names with a specific frequency in R

I have a 10x5 matrix. Each of the five columns, is named.
I need to create a vector like this:
c( rep(colnames(mymatrix)[1], dim(mymatrix)[1]),
   rep(colnames(mymatrix)[2], dim(mymatrix)[1]),
...
  rep(colnames(mymatrix)[5], dim(mymatrix)[1]))

However, what if I have a varying number of columns? How do I automate this without using a for loop?
Thanks!

A:

You can do this with the each argument to rep:
rep(colnames(mymatrix), each=dim(mymatrix)[1])

To see how this works, you can try:
v = c("h", "e", "l", "l", "o")
rep(v, each=5)
#  [1] "h" "h" "h" "h" "h" "e" "e" "e" "e" "e" "l" "l" "l" "l" "l" "l" "l" "l" "l"
# [20] "l" "o" "o" "o" "o" "o"

