Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting columns of matrix based on binary vector

Tags:

r

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
like image 336
user2806363 Avatar asked May 15 '14 03:05

user2806363


2 Answers

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
like image 136
josliber Avatar answered Oct 17 '22 06:10

josliber


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
like image 41
CHP Avatar answered Oct 17 '22 06:10

CHP