[R] Converting indices of a matrix subset
Nathan S. Watson-Haigh
nathan.watson-haigh at csiro.au
Thu Jul 9 04:20:18 CEST 2009
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
I have two matrices:
> m1 <- matrix(1,4,4)
> m1
[,1] [,2] [,3] [,4]
[1,] 1 1 1 1
[2,] 1 1 1 1
[3,] 1 1 1 1
[4,] 1 1 1 1
> m2 <- matrix(0,3,3)
> diag(m2) <- 1
> m2
[,1] [,2] [,3]
[1,] 1 0 0
[2,] 0 1 0
[3,] 0 0 1
I want to get indicies from m2 such that they match indicies as though they came
from the lower right of m1. Here's how things work:
> ind1 <- which(m1 == 1)
> ind1
[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
> ind2 <- which(m2 == 1)
> ind2
[1] 1 5 9
I would like ind2 to be offset so they look like indicies from the lower right
of m1:
> ind2
[1] 6 11 16
I can be done with a simple offset when using arr.ind=TRUE:
> ind2 <- which(m2 == 1, arr.ind=T) + 1
> ind2
row col
[1,] 2 2
[2,] 3 3
[3,] 4 4
But I don't want to use this, as I eventually want to be able to do things like:
> m1[-c(ind2)] <- 0
> m1
[,1] [,2] [,3] [,4]
[1,] 0 0 0 0
[2,] 0 1 0 0
[3,] 0 0 1 0
[4,] 0 0 0 1
Any thoughts?
Cheers,
Nathan
- --
- --------------------------------------------------------
Dr. Nathan S. Watson-Haigh
OCE Post Doctoral Fellow
CSIRO Livestock Industries
Queensland Bioscience Precinct
St Lucia, QLD 4067
Australia
Tel: +61 (0)7 3214 2922
Fax: +61 (0)7 3214 2900
Web: http://www.csiro.au/people/Nathan.Watson-Haigh.html
- --------------------------------------------------------
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org
iEYEARECAAYFAkpVU+IACgkQ9gTv6QYzVL7ClgCgtFyeyZmPyyAQbgOWSjOKEGE0
LokAoLHc08EdpgE9jZ0k4D6TWR4tzzsn
=e5pD
-----END PGP SIGNATURE-----
More information about the R-help
mailing list