[R] question on indexing of a matrix

Adaikalavan Ramasamy ramasamy at cancer.org.uk
Sat Feb 12 21:10:20 CET 2005


Extract what ? Can you please provide a simple example of how the input
looks like and the desired output. 


Here is an example of how to subscript a matrix columns from the first
level of a factor (or you can replace 1 with i for the ith level) :

f <- factor( rep( letters[1:4], 3) )
f
 [1] a b c d a b c d a b c d
Levels: a b c d

levels(f)
[1] "a" "b" "c" "d"

w <- which( f == levels(f)[1] )  # equivalent to which( f == "a" )
[1] 1 5 9


matrix <- matrix( rnorm(30), nc=10 )
matrix[ , w ]                    # returns the 1st, 5th and 9th columns 

Alternatively you can try matrix[ , which( as.numeric(f) == 1 ) ].


Note that matrix[ x, y ] subsets both the rows and columns of a matrix
which I do think is what you want to do.


Try http://cran.r-project.org/doc/manuals/R-intro.html#Array-indexing or
help("[") for how to subset a matrix or searching the mail archives.

Regards, Adai



On Sat, 2005-02-12 at 11:21 -0800, Roger Levy wrote:
> Hi,
> 
> I have a k-level factor F of length n that I would like to use to
> extract from an n-by-k matrix M a vector V such that
> 
>   V[i] = M[i,as.numeric(F)[i]]
> 
> I don't currently understand how to do that in R -- can anyone explain
> to me how to do so?
> 
> Thanks,
> 
> Roger Levy
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
>




More information about the R-help mailing list