Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a function that is opposite of paste() when editing (i.e. deleting characters from) column names of a matrix in r?

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?

like image 607
Steve Avatar asked Jan 26 '26 03:01

Steve


2 Answers

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
like image 134
Matthew Lundberg Avatar answered Jan 28 '26 19:01

Matthew Lundberg


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)
like image 22
IRTFM Avatar answered Jan 28 '26 18:01

IRTFM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!