R语言 选取某一行的最大值
可以先自定义函数,也可以用的时候再定义。
>mat<-matrix(c(1:3,7:9,4:6),byrow=T,nc=3)>mat[,1][,2][,3][1,]123[2,]789[3,]456>apply(mat,2,function(x){order(x,decreasing=T)[1]})#查找每一列[1]222>apply(mat,1,function(x){order(x,decreasing=T)[1]})#查找每一行[1]333>apply(mat,1,function(x){which.max(x)})#查找每一行[1]333>n<-letters[1:5]>n[1]"a""b""c""d""e">t<-apply(mat,1,function(x){which.max(x)})>n[t][1]"c""c""c"
另一个例子:
MaxVar<-function(x,na.rm=FALSE){##compute`max`maxx<-max(x,na.rm=na.rm)##whichequalthemaxwmax<-which(x==max(x))##howmanyequalthemaxnmax<-length(wmax)##returnout<-if(nmax>1L){c(999,NA)}else{c(maxx,wmax)}out}Anduseitlikethis:>new<-apply(Mydata[,-1],1,MaxVar)>new[,1][,2][,3][,4][,5][,6][,7][,8][,9][,10][1,]349999999994424999[2,]14NANANA4234NA>Mydata<-cbind(Mydata,Max=new[1,],Var=new[2,])>MydataIDX1X2X3X4MaxVar1131113122121444331111999NA441331999NA552221999NA6612344477243342881121239932144410104444999NA参考:http://stackoverflow.com/questions/29683339/number-of-maximums-in-each-row-and-more/29686201#29686201
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。