Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting column name which holds a max value within a row of a matrix holding a separate max value within an array

Tags:

indexing

r

max

For instance given:

dim1 <- c("P","PO","C","T")
dim2 <- c("LL","RR","R","Y")
dim3 <- c("Jerry1", "Jerry2", "Jerry3")
Q <- array(1:48, c(4, 4, 3), dimnames = list(dim1, dim2, dim3))

I want to reference within this array, the matrix that has the max dim3 value at the (3rd row, 4th column) location.

Upon identifying that matrix, I want to return the column name which has the maximum value within the matrix's (3rd Row, 1st Column) to (3rd Row, 3rd Column) range.

So what I'd hope to happen is that Jerry3 gets referenced because the number 47 is stored in its 3rd row, 4th column, and then within Jerry3, I would want the maximum number in row 3 to get referenced which would be 43, and ultimately, what I need returned (the only value I need) is then the column name which would be "R".

That's what I need to know how to do, obtain get that "R" and assign it to a variable, i.e. "column_ref", such that column_ref <- "R".

like image 448
Jonathan Charlton Avatar asked Apr 24 '12 01:04

Jonathan Charlton


2 Answers

Here's a simple way to solve:

  mxCol=function(df, colIni, colFim){ #201609
  if(missing(colIni)) colIni=1
  if(missing(colFim)) colFim=ncol(df)
  if(colIni>=colFim) { print('colIni>=ColFim'); return(NULL)}
  dfm=cbind(mxC=apply(df[colIni:colFim], 1, function(x) colnames(df)[which.max(x)+(colIni-1)])
           ,df)
  dfm=cbind(mxVal=as.numeric(apply(dfm,1,function(x) x[x[1]]))
           ,dfm)
  returndfm
}
like image 112
Everyone Avatar answered Oct 12 '22 08:10

Everyone


This should do it - if I understand correctly:

Q <- array(1:48, c(4,4,3), dimnames=list(
  c("P","PO","C","T"), c("LL","RR","R","Y"), c("Jerry1", "Jerry2", "Jerry3")))

column_ref <- names(which.max(Q[3,1:3, which.max(Q[3,4,])]))[1] # "R"

Some explanation:

which.max(Q[3,4,]) # return the index of the "Jerry3" slice (3)
which.max(Q[3,1:3, 3]) # returns the index of the "R" column (3)

...and then names returns the name of the index ("R").

like image 29
Tommy Avatar answered Oct 12 '22 09:10

Tommy