[R] How to get the row index numbers in a matrix
arun
smartpink111 at yahoo.com
Sun Jan 5 16:35:09 CET 2014
Hi,
May be this helps:
set.seed(45)
dat <- data.frame(species=rep(letters[1:3],each=5),size=sample(40,15,replace=TRUE))
dat[3,2] <- 26
mat <- as.matrix(dat)
tapply(mat[,2],mat[,1],FUN=which.max) ##assuming that you did something like this
#a b c
#1 3 2
indx <- unlist(tapply(mat[,2],mat[,1],FUN=function(x) x==max(x)),use.names=FALSE)
dat[indx,] #or mat[indx,]
# species size
#1 a 26
#3 a 26
#8 b 23
#12 c 36
#or
indx2 <-with(dat,ave(size,species,FUN=max)==size)
#or
#indx2 <- ave(mat[,2],mat[,1],FUN=max)==mat[,2]
which(indx2)
#[1] 1 3 8 12
dat[indx2,]
A.K.
Dear Friends, I have a question don't know how to resolve. I have a big
matrix. There are two colum's names"species" and "size". I have used the function "tapply" to get every maxium "size" data for every factors
"species". Now, I want to choose these rows containing maxium "size" for every factors in "species". I don't know how should I do. I know
"which()" can get the row index for one data. But, how to cope with
hundreds of data? Thank you very much!
More information about the R-help
mailing list