[R] matrix subsetting

R. Michael Weylandt <michael.weylandt@gmail.com> michael.weylandt at gmail.com
Mon Feb 13 23:46:39 CET 2012


which(x>0)

or 

which(x>0, arr.ind=TRUE)

depending on your application. 

Michael

On Feb 13, 2012, at 5:38 PM, Sam Steingold <sds at gnu.org> wrote:

> if I have a vector, I can find the indexes which satisfy a condition:
> x <- rnorm(10)
> [1]  0.4751132 -0.5442322 -0.1979854 -0.2455521  0.8349336 -0.4283345
> [7]  0.6108130  2.0576160  1.1251716 -1.3933637
> x[x>0]
> [1] 0.4751132 0.8349336 0.6108130 2.0576160 1.1251716
> (1:10)[x>0]
> [1] 1 5 7 8 9
> 
> how about a matrix?
> 
>       00000G      00000Q      00002O       000035       000037       00003A
> 00000G     NA 0.008226002 0.005631718 0.0002625585 0.0010673235 0.0045310915
> 00000Q     NA          NA 0.003714951 0.0002007877 0.0016983426 0.0011083925
> 00002O     NA          NA          NA 0.0024233691 0.0069849678 0.0024510792
> 000035     NA          NA          NA           NA 0.0006499707 0.0008420414
> 000037     NA          NA          NA           NA           NA 0.0005448872
> 00003A     NA          NA          NA           NA           NA           NA
> 00003B     NA          NA          NA           NA           NA           NA
> 00003G     NA          NA          NA           NA           NA           NA
> 00003H     NA          NA          NA           NA           NA           NA
> 00003I     NA          NA          NA           NA           NA           NA
>             00003B       00003G       00003H      00003I
> 00000G 0.0007254316 0.0093954826 3.420231e-04 0.003974556
> 00000Q 0.0013883606 0.0019778247 3.609791e-05 0.001552725
> 00002O 0.0027340806 0.0082790646 2.561862e-03 0.012297821
> 000035 0.0006025767 0.0004534397 1.053946e-03 0.001681780
> 000037 0.0005501974 0.0021137871 1.733880e-03 0.003712675
> 00003A 0.0008969849 0.0043855527 2.786194e-06 0.002492954
> 00003B           NA 0.0019791290 8.301787e-04 0.002816774
> 00003G           NA           NA 3.181892e-07 0.010608717
> 00003H           NA           NA           NA 0.001066141
> 00003I           NA           NA           NA          NA
> 
> how do I find the cells whose values are, e.g., > 0.01 ??
> 
> thanks!
> 
> -- 
> Sam Steingold (http://sds.podval.org/) on Ubuntu 11.10 (oneiric) X 11.0.11004000
> http://www.childpsy.net/ http://pmw.org.il http://americancensorship.org
> http://ffii.org http://iris.org.il http://truepeace.org http://dhimmi.com
> The difference between genius and stupidity is that genius has its limits.
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list