[R] question on indexing of a matrix

Roger Bivand Roger.Bivand at nhh.no
Sat Feb 12 21:26:46 CET 2005


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. 

> 
> 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
> 

-- 
Roger Bivand
Economic Geography Section, Department of Economics, Norwegian School of
Economics and Business Administration, Breiviksveien 40, N-5045 Bergen,
Norway. voice: +47 55 95 93 55; fax +47 55 95 93 93
e-mail: Roger.Bivand at nhh.no




More information about the R-help mailing list