简体   繁体   中英

R: Select rows of a matrix where a specific column has a specific value

I have a matrix m with 4 columns and 100 rows. The head of the matrix looks like this:

    head(m)
      [,1]  [,2]     [,3]       [,4]
 [1,] 1256 1.0000000 3.709184    0
 [2,] 8402 0.4226495 3.644793    0
 [3,]  656 0.4117985 3.165158    0
 [4,] 3925 0.4098163 3.239075    0
 [5,] 4987 0.4077779 3.471448    0
 [6,] 4715 0.4051867 3.400527    2

What I want to do is to select all the rows where the fourth column is different from 0.In the example above, I should get back :

     [,1]  [,2]     [,3]       [,4]
 [1,] 4715 0.4051867 3.400527    2        

I tried the following which command:

    m[,which(m[,4]!=0)]

but I keep getting an error " index is out of limit . What am I doing wrong? Is there an easy way to achieve what I want ?

The problem was simply a misplaced comma as eddi mentioned. The solution should be:

    m[which(m[,4]!=0),]

Also, as mentioned by mrip , the use of which is not necessary. I could have simply used:

    m[m[,4]!=0,]

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