简体   繁体   中英

Selecting columns of matrix based on binary vector

In one piece of my code, I need to select certain columns of my matrix based on binary matrix I have, and store it in the list, but I face with following problem. Does anybody know what's the problem? Here is my matrix and code:

    > data
         A  B  C  D
    [1,] 1  6 11 16
    [2,] 2  7 12 17
    [3,] 3  8 13 18
    [4,] 4  9 14 19
    [5,] 5 10 15 20

    > select<-c(1,0,1,0)

> p<-data[,select,  drop=FALSE]
> p
     A A
[1,] 1 1
[2,] 2 2
[3,] 3 3
[4,] 4 4
[5,] 5 5

My expected output is :

> p
     A  C
[1,] 1 11
[2,] 2 12
[3,] 3 13
[4,] 4 14
[5,] 5 15

You'll need to convert it to a logical vector or else it will treat 1 and 0 as column numbers:

data[,as.logical(select), drop=F]
#   A  C
# 1 1 11
# 2 2 12
# 3 3 13
# 4 4 14
# 5 5 15

You can also try. When you are just supplying select you are telling it to select columns by column number. When you are supplying select==1 you are first getting a logical vector and using that to select columns.

data <- matrix(1:20, nrow = 5, dimnames = list(NULL, c("A", "B", "C", "D")))
select <- c(1, 0, 1, 0)
data[, select == 1]
##      A  C
## [1,] 1 11
## [2,] 2 12
## [3,] 3 13
## [4,] 4 14
## [5,] 5 15

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