[R] question on indexing of a matrix

Peter Dalgaard p.dalgaard at biostat.ku.dk
Sat Feb 12 22:50:51 CET 2005


Roger Bivand <Roger.Bivand at nhh.no> writes:

> On 12 Feb 2005, 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?
> 
> This may be an answer:
> 
> > k <- 3
> > n <- 10
> > M <- matrix(1:(k*n), ncol=k, nrow=n)
> > M
>       [,1] [,2] [,3]
>  [1,]    1   11   21
>  [2,]    2   12   22
>  [3,]    3   13   23
>  [4,]    4   14   24
>  [5,]    5   15   25
>  [6,]    6   16   26
>  [7,]    7   17   27
>  [8,]    8   18   28
>  [9,]    9   19   29
> [10,]   10   20   30
> > set.seed(1234)
> > K <- factor(sample(1:3, n, replace=TRUE))
> > K
>  [1] 1 2 2 2 3 2 1 1 2 2
> Levels: 1 2 3
> > Kmm <- model.matrix(terms(~ K-1))
> > Kmm
>    K1 K2 K3
> 1   1  0  0
> 2   0  1  0
> 3   0  1  0
> 4   0  1  0
> 5   0  0  1
> 6   0  1  0
> 7   1  0  0
> 8   1  0  0
> 9   0  1  0
> 10  0  1  0
> attr(,"assign")
> [1] 1 1 1
> attr(,"contrasts")
> attr(,"contrasts")$K
> [1] "contr.treatment"
> 
> > rowSums(M * Kmm)
>  1  2  3  4  5  6  7  8  9 10 
>  1 12 13 14 25 16  7  8 19 20 
> 
> My understanding is that you want to extract the K[i]th column from the 
> [i]th row of M, so the model matrix of K should zero out the values you 
> don't want. Using something like this in a function would mean checking K 
> carefully for the number of levels actually present and their coding. 

This looks simpler:

>  M[cbind(seq(along=K),as.numeric(K))]
 [1]  1 12 13 14 25 16  7  8 19 20


-- 
   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907




More information about the R-help mailing list