[R] a little probleme

Guido Masarotto guido at sirio.stat.unipd.it
Wed Jul 4 14:30:49 CEST 2001


On Wed, Jul 04, 2001 at 01:49:50PM +0200, Olivier Martin wrote:
> i would like to find the best way to resolve the following problem.
> Suppoose i have a vector x of length N with k different elements.
> length(x)=N
> u<-unique(x)
> length(u)=k
> 
> I would like to get a matrix M with k rows and N columns such that:
> in each line i (i=1,...,k), which(x%in%u[i]) is equal to 1 and 0 else.
> 

  You can try something along the lines of the following 
  small function (sort, colnames and rownames stuff are optional)

  try.me <- function(a)
  {
    n <- length(a)
    u <- sort(unique(a))
    m <- length(u)
    ans <- matrix(0,n,m)
    ans[rep(u,rep(n,m))==a] <- 1
    colnames(ans) <- u
    rownames(ans) <- a
    ans
  }

Example:
> a <- rbinom(10,3,0.5)
> a
 [1] 1 3 2 2 1 2 0 3 1 3
> try.me(a)
  0 1 2 3
1 0 1 0 0
3 0 0 0 1
2 0 0 1 0
2 0 0 1 0
1 0 1 0 0
2 0 0 1 0
0 1 0 0 0
3 0 0 0 1
1 0 1 0 0
3 0 0 0 1
> a<-c("Chopin","Mozart","Mozart","Debussy")
> try.me(a)
        Chopin Debussy Mozart
Chopin       1       0      0
Mozart       0       0      1
Mozart       0       0      1
Debussy      0       1      0

or make use of the built-in model.matrix function which is essentially
equivalent to what you ask:

> model.matrix(~as.factor(a)-1)
  as.factor(a)Chopin as.factor(a)Debussy as.factor(a)Mozart
1                  1                   0                  0
2                  0                   0                  1
3                  0                   0                  1
4                  0                   1                  0
attr(,"assign")
[1] 1 1 1

guido



-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list