1

我正在寻找删除矩阵中每个列名的第一个字符。

mat1 <- matrix(seq(1:6), 2)
dimnames(mat1)[[2]] <- c("bA", "bB", "bC")


bA    bB    bC
1     2     3
4     5     6

进入这个:

A     B     C
1     2     3
4     5     6

我知道这个paste()函数,你可以附加到列名;有没有相反的功能?

4

3 回答 3

8

substring 是适当的函数:

 dimnames(mat1)[[2]] <- substring(dimnames(mat1)[[2]], first=2)

 mat1
     A B C
[1,] 1 3 5
[2,] 2 4 6
于 2012-11-25T23:39:30.220 回答
4

除了substring方法之外,您还可以使用正则表达式方法:

?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) )

如果有“分隔符”,您还可以使用strsplit

?strsplit
 colnames(mat1) <- sapply( strsplit( c("b_A", "b_B", "b_C"), "_"), "[", 2)
于 2012-11-26T07:55:32.487 回答
1

stri_sub包中的功能stringi

require(stringi)
stri_sub(c("aA","bB","aC"),2)
## [1] "A" "B" "C"
于 2014-04-12T10:41:51.767 回答