On Feb 7, 2011, at 12:30 PM, zhaoxing731 wrote:
Hello
I have a 100*100 matrix which is from a intensive computation, e.g.
mat. Is there any method/function that return the max of every row
and the subscript of maximum value simultaneously
#define the function
returnfunction<-function(x){
+ value<-apply(x,1,max)
+ index<-apply(x,1,which.max)
+ }
That would only return an index value
You only get a vector (about which the error message seems somewhat on
point, but a bit tangential since you did not return a named list
either so the $ extraction will not succeed) , not a matrix in the x
value passed from the apply call. Try:
returnfunction<-function(x){
value <- max(x)
index <- which.max(x)
return( c(value, index) ) }
> apply(mat,1, returnfunction)
[,1] [,2] [,3]
[1,] 4 5 10
[2,] 3 1 2
Note no row names or col names. Could get rownames with:
> returnfunction<-function(x){
+ value <- max(x)
+ index <- which.max(x)
+ return( c(val=value, ind=index) )}
> apply(mat,1, returnfunction)
[,1] [,2] [,3]
val 4 5 10
ind 3 1 2
--
David.
mat<-matrix(c(3,5,7,2,1,10,4,3,2),3)#initilize the matrix for test
mat
[,1] [,2] [,3]
[1,] 3 2 4
[2,] 5 1 3
[3,] 7 10 2
returnfunction(mat)$value
Error in returnfunction(mat)$value :
$ operator is invalid for atomic vectors
returnfunction(mat)$index
Error in returnfunction(mat)$index :
$ operator is invalid for atomic vectors
the "returnfunction(mat)$value" should be 4,5,10
the "returnfunction(mat)$index" should be 3,1,2
Thank you in advance
ZhaoXing
Department of Health Statistics
West China School of Public Health
Sichuan University
No.17 Section 3, South Renmin Road
Chengdu, Sichuan 610041
P.R.China
__________________________________________________
¸Ï¿ì×¢²áÑÅ»¢³¬´óÈÝÁ¿Ãâ·ÑÓÊÏä?
______________________________________________
[email protected] 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.
David Winsemius, MD
West Hartford, CT
______________________________________________
[email protected] 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.