Question

I want to make a boolean column which states whether or not each sample is a maximum. I made this function and used it with tapply:

is.max <- function(x){
  x <- data.frame(x)
  x$x <- round(x$x,5)
  x_max <- round(max(x),5)
  for(i in 1:nrow(x)) {
    if(x$x[i] == x_max) x$is.max[i] <- T
    else x$is.max[i] <- F
  }
return(x$is.max)
}

y <- c(rnorm(10), runif(10), rnorm(10,1))
f <- gl(3,10)
m <- tapply(y,f,is.max)

But is there a better, efficient way to do that?

{P.S. Actually with my real data I used sapply, e.g. is.maxes<-sapply(s, function(x) is.max(x[,"Sum"]),simplify=F)}

Was it helpful?

Solution

Yeah, you can use do this in one line with tapply:

tapply(y,f,function(x) round(x,5)==round(max(x),5))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top