Hello, I would like to find the maximum element in a matrix or an array but it does not return what I want. For example, If I have a 2*2 matrix A whose maximum element is the A(1,2). I would like the answer (1,2), but it returns 3, which is the ordinal if one counts by columns. Is there any function that returns (1,2)? Thanks> A<-rbind(c(1,4), c(3,2))> A [,1] [,2][1,] 1 4 [2,] 3 2> which.max(A)[1] 3 [[alternative HTML version deleted]]
R. Michael Weylandt
2012-Mar-30 02:39 UTC
[R] Finding the maximum elements in an array/matrix
As they say, RTFM....in particular, this part: ? which.max --> See Also: Use ?arrayInd()?, if you need array/matrix indices instead of 1D vector ones. Michael On Thu, Mar 29, 2012 at 10:27 PM, jpm miao <miaojpm at gmail.com> wrote:> Hello, > > ? I would like to find the maximum element in a matrix or an array but it > does not return what I want. > > ? For example, If I have a 2*2 matrix A whose maximum element is the > A(1,2). I would like the answer (1,2), but it returns 3, which is the > ordinal if one counts by columns. Is there any function that returns (1,2)? > > > ? Thanks > >> A<-rbind(c(1,4), c(3,2))> A ? ? [,1] [,2] > [1,] ? ?1 ? ?4 > [2,] ? ?3 ? ?2> which.max(A)[1] 3 > > ? ? ? ?[[alternative HTML version deleted]] > > ______________________________________________ > R-help at r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code.
Try which(A == max(A), arr.ind = TRUE) HTH, Jorge.- On Thu, Mar 29, 2012 at 10:27 PM, jpm miao <> wrote:> Hello, > > I would like to find the maximum element in a matrix or an array but it > does not return what I want. > > For example, If I have a 2*2 matrix A whose maximum element is the > A(1,2). I would like the answer (1,2), but it returns 3, which is the > ordinal if one counts by columns. Is there any function that returns (1,2)? > > > Thanks > > > A<-rbind(c(1,4), c(3,2))> A [,1] [,2] > [1,] 1 4 > [2,] 3 2> which.max(A)[1] 3 > > [[alternative HTML version deleted]] > > ______________________________________________ > R-help@r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide > http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. >[[alternative HTML version deleted]]
Apparently Analagous Threads
- What is a better way to deal with lag/difference and loops in time series using R?
- Why can't R understand if(num!=NA)?
- Definition of "lag" is opposite in ts and xts objects!
- How can we access an element in a structure
- How can I tabulate time series data (in RStudio or any other R editor)?