Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent to rowMeans() for min()

Tags:

I have seen this question being asked multiple times on the R mailing list, but still could not find a satisfactory answer.

Suppose I a matrix m

m <- matrix(rnorm(10000000), ncol=10)  

I can get the mean of each row by:

system.time(rowMeans(m))      user  system elapsed      0.100   0.000   0.097 

But obtaining the minimum value of each row by

system.time(apply(m,1,min))      user  system elapsed     16.157   0.400  17.029 

takes more than 100 times as long, is there a way to speed this up?

like image 733
johannes Avatar asked Jun 14 '11 02:06

johannes


People also ask

How do I sum two rows in R?

First of all, create a data frame. Then, using plus sign (+) to add two rows and store the addition in one of the rows. After that, remove the row that is not required by subsetting with single square brackets.

How do I sum a row in R?

Calculating the sum of rows of the array in R To calculate the sum of rows of an array in R, use the rowSums() function. Let's create an array and use the rowSums() function to calculate the sum of rows of the array. To create an array in R, use the array() function.

How do you find the mean of a row in R?

The rowMeans() function in R can be used to calculate the mean of several rows of a matrix or data frame in R.

What is rowMeans R?

The rowMeans() is a built-in R function that calculates the mean of each row of a matrix or array. The rowMeans() method returns the mean for the specified rows for the data frame, matrix, or arrays. The rowMeans() function is very useful when you want to find the mean values rows.


1 Answers

You could use pmin, but you would have to get each column of your matrix into a separate vector. One way to do that is to convert it to a data.frame then call pmin via do.call (since data.frames are lists).

system.time(do.call(pmin, as.data.frame(m))) #    user  system elapsed  #   0.940   0.000   0.949  system.time(apply(m,1,min)) #    user  system elapsed  #   16.84    0.00   16.95  
like image 87
Joshua Ulrich Avatar answered Oct 22 '22 19:10

Joshua Ulrich