[R] arrayInd and which
David Winsemius
dwinsemius at comcast.net
Fri Apr 5 21:51:30 CEST 2013
On Apr 5, 2013, at 8:07 AM, R. Michael Weylandt wrote:
> On Fri, Apr 5, 2013 at 2:08 PM, Keith S Weintraub <kw1958 at gmail.com> wrote:
>> And to the rest of you good R folks I would still be interested to see a working example of arrayInd, what it's supposed to do and what it's used for.
>
> A little utility function for dealing with the
> matrix-is-really-a-vector indexing duality. (Elemental (1,3) vs linear
> #4 indexing)
>
> E.g.,
>
> x <- matrix(rnorm(9), 3, 3)
>
> which.min(x) # Not super helpful
>
> where.min <- function(x) arrayInd(which.min(x), dim(x), dimnames(x), T)
>
> where.min(x) # Perhaps better
>
mat <- matrix( rnorm(100), 5,5)
colnames(mat) <- c("one", "two", "three", "four","five")
rownames(mat) <- paste0("R.", colnames(mat))
locations <- which( mat > 1, arr.ind=TRUE)
> locations
row col
[1,] 2 1
[2,] 3 2
[3,] 3 3
[4,] 5 5
> mat
one two three four five
R.one -0.5275761 -0.02992900 -0.8109619 0.58535983 0.14943981
R.two 1.0987958 -0.05218127 -0.9662047 -0.09937671 -0.03827459
R.three -1.3544322 2.44794695 1.3371429 -0.52141363 -0.83303343
R.four -0.4668546 -1.85648092 -0.6528013 0.10810654 0.34591032
R.five -1.0112662 -0.13317105 -1.3125148 0.06381063 1.27742711
data.frame(cols = colnames(mat)[locations[,2]], rows = rownames(mat)[locations[,1]], values=mat[locations])
cols rows values
1 one R.two 1.098796
2 two R.three 2.447947
3 three R.three 1.337143
4 five R.five 1.277427
> Cheers,
> Michael
David Winsemius
Alameda, CA, USA
More information about the R-help
mailing list