I'm looking to remove the first character of every column name in a matrix.
mat1 <- matrix(seq(1:6), 2)
dimnames(mat1)[[2]] <- c("bA", "bB", "bC")
bA bB bC
1 2 3
4 5 6
into this:
A B C
1 2 3
4 5 6
I know with the paste() function, you can append to the column names; is there a function that does the opposite?
substring is the appropriate function:
dimnames(mat1)[[2]] <- substring(dimnames(mat1)[[2]], first=2)
mat1
A B C
[1,] 1 3 5
[2,] 2 4 6
Besides the substring approach you can use regex methods:
?regex
colnames(mat1) <- sub('^\\.', "", colnames(mat1) ) # removes first letter
# the next one removes lower-case letters which for some reason Jilber has already posted but deleted
colnames(mat1) <- sub("[a-z]", "", colnames(mat1) )
If there were "separators" you can also use strsplit:
?strsplit
colnames(mat1) <- sapply( strsplit( c("b_A", "b_B", "b_C"), "_"), "[", 2)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With