简体   繁体   中英

removing columns in R matrix using column names - independent of order

I am having trouble with removing columns in a matrix using column names - the output is dependent on the order of the column names.

matrix <- matrix(c(1,2,3,4,5,6,7,8,9,10,11,12), 3,4,dimnames = list(c("R1","R2","R3"), c("C1","C2","C3","C4")))

setA <- c("C2","C3")
setB <- c("C3","C2")

matrixA <- matrix[, colnames(matrix)!=setA]
matrixB <- matrix[, colnames(matrix)!=setB]

i was expecting the output the same in the both cases (expected output is output of matrixB)

however, the actual output i got was:

> matrixA
   C1 C2 C3 C4
R1  1  4  7 10
R2  2  5  8 11
R3  3  6  9 12
> matrixB
   C1 C4
R1  1 10
R2  2 11
R3  3 12

In my actual problem, i wil have to choose the elements of setA in a random order. How do i make sure that the columns are actually removed?

That is because the elements of setA and setB are recyecled to have the same length as colnames(matrix) .

setA will become c("C2", "C3", "C2", "C3") when used in colnames(matrix)!=setA . Likewise, setB will become c("C3", "C2", "C3", "C2") when used in colnames(matrix)!=setB . That is why all columns are selected for setA and only 2 columns are selected for setB .

colnames(matrix)
[1] "C1" "C2" "C3" "C4"

colnames(matrix)!=setA
[1] TRUE TRUE TRUE TRUE

colnames(matrix)!=setB
[1]  TRUE FALSE FALSE  TRUE

You can use the following to omit the columns you don't want.

!colnames(matrix) %in% setB
[1]  TRUE FALSE FALSE  TRUE

Try


matrix[,!colnames(matrix)%in%YOURSET]

> identical(matrix[,!colnames(matrix)%in%setA],
            matrix[,!colnames(matrix)%in%setB])

[1] TRUE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM