[R] matrix manipulation

Petr Savicky savicky at cs.cas.cz
Thu Jun 14 20:48:44 CEST 2012


On Thu, Jun 14, 2012 at 02:24:20PM -0400, cowboy wrote:
> thank you, Petr.
> This is exactly what I'm looking for in my post.
> An related question can be how to get an arbitrary weight, say if row1
> and row 2 have 1 common value 1, then assign a weight 10, if row 1 and
> row 2 have 2 common value 1, then assign a weight 12. I'm not so sure
> how to expand your method.

Hi.

The weight matrix may be transformed. Try the following.

  # modified example to have also intersection 2
  a <- rbind(
  c(0, 1, 1, 1),
  c(1, 0, 1, 1),
  c(0, 0, 0, 1))

  w <- a %*% t(a)
  diag(w) <- 0
  w

       [,1] [,2] [,3]
  [1,]    0    2    1
  [2,]    2    0    1
  [3,]    1    1    0

  trans <- c(1, 10, 12)
  w[, ] <- trans[w + 1]
  w

       [,1] [,2] [,3]
  [1,]    1   12   10
  [2,]   12    1   10
  [3,]   10   10    1

Hope this helps.

Petr Savicky.



More information about the R-help mailing list