Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

max and min functions that are similar to colMeans

Tags:

r

I am wondering if there are high speed min and max function that works on columns similarly to colMeans?

For 'max', although I can simulate the behavior with 'apply' such as the following:

colMax <- function (colData) {
    apply(colData, MARGIN=c(2), max)
}

It seems a lot slower than the colMeans in the base package.

like image 486
defoo Avatar asked Oct 19 '11 16:10

defoo


People also ask

How do you find min and max in R?

In R, we can find the minimum or maximum value of a vector or data frame. We use the min() and max() function to find minimum and maximum value respectively. The min() function returns the minimum value of a vector or data frame. The max() function returns the maximum value of a vector or data frame.

How do you find the maximum value of a function in R?

max() in R The max() is a built-in R function that finds the maximum value of the vector or data frame. It takes the R object as an input and returns the maximum value out of it. To find the maximum value of vector elements, data frame, and columns, use the max() function.

How do you find the minimum value in R?

Minimum value of a column in R can be calculated by using min() function. min() Function takes column name as argument and calculates the Minimum value of that column.


1 Answers

pmax is ~ 10x faster than apply. Still not as fast as colMeans though.

data = matrix(rnorm(10^6), 100)
data.df = data.frame(t(data))

system.time(apply(data, MARGIN=c(2), max))
system.time(do.call(pmax, data.df))
system.time(colMeans(data))
> system.time(apply(data, MARGIN=c(2), max))
   user  system elapsed 
  0.133   0.006   0.139 
> system.time(do.call(pmax, data.df))
   user  system elapsed 
  0.013   0.000   0.013 
> system.time(colMeans(data))
   user  system elapsed 
  0.003   0.000   0.002
like image 191
John Colby Avatar answered Sep 20 '22 15:09

John Colby