这是一个更通用的解决方案,它将删除第 1 行条目中的任何字母与第 2 行条目中的任何字母 匹配的列:
## Your data
chars <- c("A1","A2","B1","B2")
charsmat <- combn(chars, 2)
vetMatrix <- function(mat) {
## Remove non-alpha characters from matrix entries
mm <- gsub("[^[:alpha:]]", "", mat)
## Construct character class regex patterns from first row
patterns <- paste0("[", mm[1,], "]")
xs <- mm[2,]
## Extract columns in which no character in first row is found in second
mat[,!mapply("grepl", patterns, xs), drop=FALSE]
}
## Try it with your matrix ...
vetMatrix(charsmat)
# [,1] [,2] [,3] [,4]
# [1,] "A1" "A1" "A2" "A2"
# [2,] "B1" "B2" "B1" "B2"
## ... and with a different matrix
mat <- matrix(c("AB1", "B1", "AA11", "BB22", "this", "that"), ncol=3)
mat
# [,1] [,2] [,3]
# [1,] "AB1" "AA11" "this"
# [2,] "B1" "BB22" "that"
vetMatrix(mat)
# [,1]
# [1,] "AA11"
# [2,] "BB22"