Print colnames inside each vector for a matrix

Hello,
I have a matrix with many columns. I want to do this operation for the entire matrix.
Example:
exam_1
After operation
exam_2

Thanks.
Rafael Navarro

Does this do what you want?

MAT <- matrix(1:16, nrow = 4)
dimnames(MAT) <- list(c("A","B","C","D"), c("AA","BB","CC","DD"))
MAT
#>   AA BB CC DD
#> A  1  5  9 13
#> B  2  6 10 14
#> C  3  7 11 15
#> D  4  8 12 16
sapply(colnames(MAT), function(Nm) paste(MAT[,Nm], Nm, sep = "_"))
#>      AA     BB     CC      DD     
#> [1,] "1_AA" "5_BB" "9_CC"  "13_DD"
#> [2,] "2_AA" "6_BB" "10_CC" "14_DD"
#> [3,] "3_AA" "7_BB" "11_CC" "15_DD"
#> [4,] "4_AA" "8_BB" "12_CC" "16_DD"

Created on 2023-04-28 with reprex v2.0.2

1 Like

Yes. I just added a conditional for "0":
function(Nm) ifelse(x[, Nm] == "0", "",paste(x[, Nm], Nm, sep = "_"))

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.