我正在寻找删除矩阵中每个列名的第一个字符。
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()
函数,你可以附加到列名;有没有相反的功能?
substring 是适当的函数:
dimnames(mat1)[[2]] <- substring(dimnames(mat1)[[2]], first=2)
mat1
A B C
[1,] 1 3 5
[2,] 2 4 6
除了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)
stri_sub
包中的功能stringi
。
require(stringi)
stri_sub(c("aA","bB","aC"),2)
## [1] "A" "B" "C"