Skip to content
Prev 156324 / 398506 Next

Re adout row and column of a matrix value

On Sep 17, 2008, at 3:36 PM, Jorge Ivan Velez wrote:

            
I wasn't sure that max(x) or whatever target was specified would be  
unique, and in the test case I set up    c(which(...)    did not  
maintain the matrix structure, it just appended a vector of row  
numbers to column numbers and added one max().

Perhaps consider:

x <- matrix(sample(1:10,64,replace=TRUE), nrow=8)
wmtx <- which(x==max(x), arr.ind=TRUE)  # a matrix with row and column  
numbers
wvmtx <- cbind(wmtx,val=max(x)) #argument recycling
df <- as.data.frame(wvmtx)
#if you really need to convert the value to a character then use  
as.character
df$val <- as.character(df$val)
#-------
 > str(df)
'data.frame':	8 obs. of  3 variables:
  $ row: int  1 3 5 5 7 8 4 7
  $ col: int  1 3 3 4 6 6 8 8
  $ val: chr  "10" "10" "10" "10" ...

write.csv(df, <filepath,filename> )