Search code examples
rseqrep

Specifying column names with a defined structure


Assume I've a (used defined covariance) matrix and I want define the column names like this:

y <- matrix(rnorm(15*10),ncol=15)

colnames(y) <- c("Var1", "Cov12", "Cov13","Cov14", "Cov15",
"Var2", "Cov23", "Cov24", "Cov25", 
"Var3", "Cov34" , "Cov35"      
"Var4", "Cov45", 
"Var5")

where each row contained the variance or co variance for an date t. I want to find a more general way to assign the column names as above, because I'll not always have 5 different variances. I tried something with rep and seq but I didn't find a solution.


Solution

  • Maybe not the most optimal way but we can do

    n <- 5
    paste0("Var", rep(1:n, n:1), unlist(sapply(2:n, function(x) c("",seq(x, n)))))
    
    [1] "Var1"  "Var12" "Var13" "Var14" "Var15" "Var2"  "Var23" "Var24" "Var25" "Var3"   
        "Var34" "Var35" "Var4"  "Var45" "Var5"
    

    Breaking it down for better understanding

    rep(1:n, n:1)
    #[1] 1 1 1 1 1 2 2 2 2 3 3 3 4 4 5
    
    unlist(sapply(2:n, function(x) c("",seq(x, n))))
    #[1] ""  "2" "3" "4" "5" ""  "3" "4" "5" ""  "4" "5" ""  "5"
    

    We take these outputs and paste them parallely with "Var" to get the desired column names.