1

I am trying to create some column names with paste. I think this is quite simple, however I am not knowing a function that could I use for my purposes

Assume I've the following matrix:

X <- matrix(rnorm(100,1,1), ncol=10)
colnames(X)=NULL

The expected output should be:

colnames(X) <- c("l1.1", "l2.1", "l3.1", "l4.1", "l5.1", "l1.2", "l2.2", "l3.2", "l4.2", "l5.2")

But in a very general way to assign this structure for high dimensional purposes. In particular I've 5 variables (first number) and the 2nd number is assigning the lag number of the variable

Leo96
  • 489
  • 3
  • 12
  • Question in unclear, please read and edit your question according to: [How to make a great R reproducible example?](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) Add code that you have tried, input and wanted output . – pogibas Jul 16 '18 at 08:04
  • edited a bit to make things more clear – Leo96 Jul 16 '18 at 08:12

2 Answers2

3
paste0("l", rep(1:5, times = 2), ".", rep(1:2, each = 5))
 [1] "l1.1" "l2.1" "l3.1" "l4.1" "l5.1" "l1.2" "l2.2" "l3.2" "l4.2"
[10] "l5.2"

Can be shortened to (because if recycling):

paste0("l", 1:5, ".", rep(1:2, each = 5))

But I like the logic of the sprintf() more:

sprintf("l%d.%d", 1:5, rep(1:2, each = 5))

There is also this new package called glue:

library(glue)
glue("l{n1}.{n2}", n1 = rep(1:5, times = 2), n2 = rep(1:2, each = 5))
s_baldur
  • 29,441
  • 4
  • 36
  • 69
2

Is this what you're looking for?

paste0("l", rep(seq(1,5,1),2), ".", rep(seq(1,2,1), each=5))

[1] "l1.1" "l2.1" "l3.1" "l4.1" "l5.1" "l1.2" "l2.2" "l3.2" "l4.2" "l5.2"

SeGa
  • 9,454
  • 3
  • 31
  • 70