下面是一個更一般的解決方案,它將刪除列中的任何行中的任何字母匹配任意字母行2中的en請嘗試:
## 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"
謝謝一噸;我很感激。 – ahj 2012-07-17 19:23:18